一、Hibernate是什么
Hibernate是一个面向Java环境采用对象/关系映射机制的持久化框架。
对象/关系型数据库映射(Object/relational mapping,ORM),在Java中即表示Java对象与关系型数据库表间的映射。除此之外,Hibernate还提供了大量的数据操作方法。与JDBC相比,Hibernate大大简化了对数据库的操作。
持久化:将程序数据在瞬时状态和持久状态之间转换的机制。瞬时状态:保存在内存的程序数据,程序退出后,数据就会消失,称之为瞬时状态。持久状态:保存在磁盘上的程序数据,程序退出后依然存在,成为持久状态。
二、Hibernate的配置
1、添加Hibernate依赖支持
2、添加Hibernate配置文件
hibernate.cfg.xml(该配置文件,展示了一个仅配置了数据源的一个hibernate配置文件)
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/school</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
</session-factory>
</hibernate-configuration>
3、添加对应表的实体类和映射文件
实体类就是一个普通的JavaBean,一个用户的实体类代码示例:
User.java
public class User implements java.io.Serializable {
private Integer id;
private String username;
private String password;
private String email;
private String sex;
private Date createTime;
private Date loginTime;
//省略getter、setter方法
}
映射文件是Hibernate定义的作为实体类和关系数据库中的表映射使用的配置文件,用户实体对应的映射文件示例如下:
User.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.boya.hibernate.entity.User" table="user" catalog="easybbs">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned" />
</id>
<property name="username" type="java.lang.String">
<column name="username" length="50" />
</property>
<property name="password" type="java.lang.String">
<column name="password" length="50" />
</property>
<property name="email" type="java.lang.String">
<column name="email" length="50" />
</property>
<property name="sex" type="java.lang.String">
<column name="sex" length="50" />
</property>
<property name="createTime" type="java.util.Date">
<column name="create_time" length="19" />
</property>
<property name="loginTime" type="java.util.Date">
<column name="login_time" length="19" />
</property>
</class>
</hibernate-mapping>
通过映射文件中的class标签,我们可以看到,实体类User和数据库表user表的一个映射关系。然后,依次设定了主键生成策略,以及其他属性与字段间的映射关系。
添加完毕之后,需要将该映射信息加入到hibernate的配置文件中,在hibernate.cfg.xml中加入如下配置:
<mapping resource="com/boya/hibernate/entity/User.hbm.xml" />
至此,hibernate配置就完成了,我们就可以在程序中使用hibernate了。
三、使用Hibernate的步骤
1、读取配置文件Configuration conf = new Configuration().configure();2、创建SessionFactorySessionFactory sf = conf.buildSessionFactory();3、打开SessionSession session = sf.openSession();4、开启事务Transaction tx = session.beginTransaction();5、持久化操作User user = new User();user.setUsername("Hibernate user");user.setPassword("password");session.save(user);6、提交事务tx.commit();7、关闭Sessionsession.close();
四、对Hibernate的简单封装
封装Hibernate的基本步骤,将session使用threadLocal绑定线程,线程终止时session自动销毁,可以不去手动关闭Session。具体代码如下:(MyEclipse自动生成)
完整代码示例: http://download.csdn.net/detail/boyazuo/5105994
package com.boya.hibernate.dao;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return session factory
*
* session factory will be rebuilded in the next call
*/
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
在我们自己的Dao中,使用代码示例如下:
public class UserDao{
public void save(User user){
try {
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
public List findAll(){
String hql = "from User";
Session session = HibernateSessionFactory.getSession();
return session.createQuery(hql).list();
}
//others....
}
完整代码示例: http://download.csdn.net/detail/boyazuo/5105994