Hibernate概述
l What is Hibernate?
Hibernate是用于简化数据库操作的第三方开源工具.它实现ORM(Object-Relational Mapping,对象关系映射),在具体的操作业务对象时,就不需要和复杂的SQL语句打交道,只要像平时操作对象一样.
l Why use hibernate?
如果不使用hibernate的话,那么就会出现很多重复的代码,
Eg:
在DAO中,假设存在createUser(),updateUser(),removeUser()方法,则在每个方法里,我们都需要使用JDBC连接数据库,我们需要重复装载类,使用连接字符串、用户名、密码来连接数据库的工作,很繁琐.使用Hibernate可以解决这个问题.
l How to use hibernate?
当然得导入相应的包,这个过程就不再累赘了.
然后需要配置Hibernate,
在工程目录/src下,新建hibernate.properties,
Eg:
hibernate.dialect=net.sf.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=org.gjt.mm.mysql.Driver
hibernate.connection.url=jdbc:mysql://localhost:3306/login
hibernate.connection.username=root
hibernate.connection.password=123654
hibernate.show_sql=true
再新建hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration
PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
<!--Mapping files-->
<!--唯一需要修改的位置-->
<mapping resource="login3/db/hibernate/dao/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
其中主要内容就是加粗部分,它告诉Hibernate,对象关系映射文件在login3/db/hibernate/dao/User.hbm.xml
接着就是配置User.hbm.xml
Eg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<!--定于类和表的映射-->
<class name="login3.db.kingdao.dto.UserDTO" table="user">
<!--关系一端的主键定义-->
<id name="userId" column="userId">
<generator class="increment" />
</id>
<!--属性和列的映射-->
<property name="username" column="username" />
<property name="password" column="password" />
</class>
</hibernate-mapping>
这样的话,就把关系数据库和对象login3.db.kingdao.dto.UserDTO连接起来了..
在访问数据库的代码中,步骤都差不多.直接看example

try{
//获取Session Factory
SessionFactory sf = new
Configuration().configure().buildSessionFactory();
//获取Session
Session session = sf.openSession();
//事务控制
Transaction tx = session.beginTransaction();
//添加记录
session.save(user);
//事物提交
tx.commit();
//关闭session
session.close();
}

catch (Exception e) {
e.printStackTrace();
}
//eg: 更新记录的代码
UserDTO _user = (UserDTO) session.load(UserDTO.class, user.getUserId());
_user.setPassword(user.getPassword());
session.flush();
//eg: 删除记录
session.delete("from UserDTO where userId = '" + _userId + "'");
//eg: 查找记录,这个可以不用transaction对象
List results = (List) session.find("from UserDTO where userId='" +_userId + "'");
PS:hibernate 5个核心接口的类关系图: