Hibernate工作原理及为什么要用?
原理:
1.读取并解析配置文件
2.读取并解析映射信息,创建SessionFactory
3.打开Sesssion
4.创建事务Transation
5.持久化操作
6.提交事务
7.关闭Session
8.关闭SesstionFactory
配置文件
在使用Hibernate時,還必須定義一個设定文件,告知数据库名稱、用户名稱、密碼、映射文件位置等,可以使用XML檔案來定義,檔名為hibernate.cfg.xml
映射文件
User類別與user表格之間要建立對映關係,實際上是靠一個映射文件來完成,映射文件可以使用XML來撰寫,通當命名為.hbm.xml,例如設計一個User.hbm.xml映射文件
启动Session
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
....
// 建立DAO物件
IUserDAO userDAO = new UserDAO(sessionFactory);
User user = new User();
user.setName("caterpillar");
user.setAge(new Integer(30));
userDAO.insert(user);
user = userDAO.find(new Integer(1));
System.out.println("name: " + user.getName());
....
tx.commit();
session.close();
Session与SessionFactory
Session是由SessionFactory所創建,SessionFactory是執行緒安全的(Thread-safe),您可以讓多個執行緒同時存取SessionFactory而不會有資料共用的問題,然而Session則不是設計為執行緒安全的,所以試圖讓多個執行緒共用一個 Session,將會發生資料共用而發生混亂的問題。
由於Thread-Specific Stroage模式可以有效隔離執行緒所使用的資料,所以避開Session的多執行緒之間的資料共用問題,以下列出Hibernate參考手冊中的 HibernateUtil類
import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil
{
private static Log log = LogFactory.getLog(HibernateUtil.class);
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch (Throwable ex)
{
// Make sure you log the exception, as it might be swallowed
log.error("Initial SessionFactory creation failed.", ex);
throw new ExceptionInInitializerError(ex);
}
}
public static final ThreadLocal session = new ThreadLocal();
public static Session currentSession()
{
Session s = (Session) session.get();
// Open a new Session, if this Thread has none yet
if (s == null)
{
s = sessionFactory.openSession();
session.set(s);
}
return s;
}
public static void closeSession()
{
Session s = (Session) session.get();
if (s != null)
s.close();
session.set(null);
}
}
在同一個執行緒中,Session被暫存下來了,但無須擔心資料庫連結Connection持續占用問題,Hibernate會在真正需要資料庫操作時才(從連接池中)取得Connection。
在程式中可以這麼使用HibernateUtil:
Session session = HibernateUtil.currentSession();
User user = (User) session.load(User.class, new Integer(1));
System.out.println(user.getName());
HibernateUtil.closeSession();
实体对象生命周期