Hibernate记录

[b]Hibernate工作原理及为什么要用? [/b]
原理:
1.读取并解析配置文件
2.读取并解析映射信息,创建SessionFactory
3.打开Sesssion
4.创建事务Transation
5.持久化操作
6.提交事务
7.关闭Session
8.关闭SesstionFactory


[b]配置文件[/b]
在使用Hibernate時,還必須定義一個设定文件,告知数据库名稱、用户名稱、密碼、映射文件位置等,可以使用XML檔案來定義,檔名為hibernate.cfg.xml

[b]映射文件[/b]
User類別與user表格之間要建立對映關係,實際上是靠一個映射文件來完成,映射文件可以使用XML來撰寫,通當命名為.hbm.xml,例如設計一個User.hbm.xml映射文件

[b]启动Session[/b]
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();


[b]Session与SessionFactory[/b]
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();



[b]实体对象生命周期[/b]

[img]http://dl.iteye.com/upload/attachment/305005/8bdbf575-aed1-311c-a7ea-da0b487b349c.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值