Hibernate是一个开源的ORM框架,顾名思义,它的核心思想即ORM(Object Relational Mapping,对象关系映射),可以通过对象来操作数据库中的信息,据说开发者一开始是不太熟悉数据库SQL语句的,这也造就了hibernate的强大之处,它不强求开发者熟悉SQL语句也可以操作数据库,hibernate可以自动生成SQL语句,自动执行。
利用hibernate可以让开发者完全使用面想对象思维来操作数据库,所以接下来的演示不会有一句SQL语句,如果有的话,请当我这句话没说!
本文使用hibernate实现了简单的对一个person数据表的基本增删改查操作。
准备工作
环境:win7+eclipse
工具包:hibernate包,可前往http://hibernate.org/orm/downloads/下载,本例中使用的是4版本;
数据库连接驱动包,本例中使用的是mysql的
程序结构图示
pojo层实体类
package demo.pojo;
public class Person {
private Integer id;
private String name;
private String gender;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", gender=" + gender + ", age=" + age + "]";
}
}
核心配置文件hibernate.cfg.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 <hibernate-configuration> 6 <session-factory> 7 <!-- 以下四行分别为:数据库驱动类、Drivermanager获取连接的参数URL、用户名、密码 --> 8 <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 9 <property name="connection.url">jdbc:mysql://127.0.0.1/web?characterEcoding=utf-8</property> 10 <property name="connection.username">root</property> 11 <property name="connection.password">123456</property> 12 <!-- 设置方言,hibernate会根据数据库的类型相应生成SQL语句 --> 13 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 14 15 <!-- 控制台显示生成的sql语句,默认为false --> 16 <property name="show_sql">true</property> 17 <!-- 映射配置源文件的位置 --> 18 <mapping resource="demo/pojo/Person.hbm.xml"/> 19 </session-factory> 20 21 </hibernate-configuration>
映射文件Person.hbm.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 <hibernate-mapping> 6 <!-- name是实体类全名,table为数据表名 --> 7 <class name="demo.pojo.Person" table="Person"> 8 <id name="id" column="id"> 9 <!-- 主键生成方式,native是让hibernate自动识别 --> 10 <generator class="native"></generator> 11 </id> 12 <!-- 13 注意点: 14 0.name值为实体类中属性名,column为数据表中字段名; 15 1.当实体类中属性名与对应数据表字段名相同时,后面的column可以省略,hibernate会自动匹配,例如下面age ; 16 2.反之当实体类中属性名与对应数据表字段名不相同时,两项都要写上,例如下面gender和sex 17 --> 18 <property name="name" column="name"></property> 19 <property name="gender" column="sex"></property> 20 <property name="age"></property> 21 </class> 22 </hibernate-mapping>
Session工厂类
1 package demo.util; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.cfg.Configuration; 6 import org.hibernate.service.ServiceRegistry; 7 import org.hibernate.service.ServiceRegistryBuilder; 8 9 public class HibernateSessionFactory { 10 private static SessionFactory factory; 11 private static ThreadLocal<Session> thread = new ThreadLocal<Session>(); 12 private static String path = "hibernate.cfg.xml"; 13 private static Configuration config = new Configuration(); 14 static { 15 config.configure(path); 16 ServiceRegistry service = new ServiceRegistryBuilder()//定义一个服务*** 17 .applySettings(config.getProperties()).buildServiceRegistry(); 18 factory = config.buildSessionFactory(service);//创建Session工厂类 19 } 20 21 public static Session getSession() { 22 Session session = thread.get(); 23 if(session == null || !session.isOpen()) { 24 session = factory.openSession(); 25 thread.set(session); 26 } 27 return session; 28 } 29 30 public static void closeSession() { 31 Session session = thread.get(); 32 if(session != null && session.isOpen()) { 33 session.close(); 34 thread.set(null); 35 } 36 } 37 38 }
DAO层封装数据各项操作的方法
1 package demo.dao; 2 3 import java.io.Serializable; 4 import org.hibernate.Session; 5 import org.hibernate.Transaction; 6 import demo.pojo.Person; 7 import demo.util.HibernateSessionFactory; 8 9 public class PersonDaoImpl { 10 //增删改查,此处以增为例 11 public boolean add(Person p) { 12 Session session = HibernateSessionFactory.getSession();//创建Session 13 Transaction trans = session.beginTransaction();//开启事务 14 try { 15 Serializable id = session.save(p);//添加记录并获取主键值 16 System.out.println(id+"为获取的主键值");//控制台查看主键值 17 trans.commit();//提交事务 18 return true; 19 } catch (Exception e) { 20 trans.rollback();//获取异常,则事务回滚 21 } finally { 22 HibernateSessionFactory.closeSession();//关闭Session 23 } 24 return false; 25 } 26 }
测试类TestPerson
1 package demo.test; 2 3 import org.junit.Test; 4 import demo.dao.PersonDaoImpl; 5 import demo.pojo.Person; 6 7 public class TestPerson { 8 @Test 9 public void testAdd() { 10 //创建一个人类对象 11 Person p = new Person(); 12 p.setName("张三"); 13 p.setGender("男"); 14 p.setAge(18); 15 //创建dao层类对象并调用添加方法 16 PersonDaoImpl dao = new PersonDaoImpl(); 17 dao.add(p); 18 } 19 }