Home >Database >Mysql Tutorial >Hibernate_HelloWorld
一、Hello World Hibernate搭建环境 1、建立一个Project,导入数据库驱动程序,Hibernate所需的jar包 2、创建model层,创建Student类,分别设定id,name,age属性及setter()和getter()方法 3、编写hibernate.cfg.xml ?xml version=1.0 encoding=utf-8?!DOCTYPE
Hibernate搭建环境
1、建立一个Project,导入数据库驱动程序,Hibernate所需的jar包
2、创建model层,创建Student类,分别设定id,name,age属性及setter()和getter()方法
3、编写hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhos【本文来自鸿网互联 (http://www.68idc.cn)】t:3306/hibernate</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <!-- <property name="connection.pool_size">1</property> --> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <!-- <property name="current_session_context_class">thread</property> --> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <!-- <property name="hbm2ddl.auto">update</property> --> <mapping resource="com/zgy/hibernate/model/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
4、编写Student.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping > <class name="com.zgy.hibernate.model.Student" table="student"> <id name="id" column="id"></id> <property name="name" column="name"></property> <property name="age" column="age"></property> </class> </hibernate-mapping>
5、连接本地数据库,创建数据库hibernate和表student
create database hibernate; use hibernate; create table student(id int primary key, name varchar(20), age int);
6、创建测试类StudentTest.java
package com.zgy.hibernate.model; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class StudentTest { public static void main(String[] args){ Student s = new Student(); s.setId(1); s.setName("s1"); s.setAge(1); Configuration cfg = new Configuration(); SessionFactory sf = cfg.configure().buildSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); sf.close(); } }
7、运行,测试成功