在Spring+Hibernate中提供的DAO封装

来源:互联网 发布:硅谷软件学校 编辑:程序博客网 时间:2024/06/07 13:02
在Spring和Hibernate中,Spring提供了很多Hibernate的DAO封装。

========================================JDBC操作

//获得SessionFactory
SessionFactory sf = super.getSessionFactory();
Connection conn = null;
PreparedStatement pstmt = null;

1、从缓冲池获得数据库连接(org.hibernate.connection.ConnectionProvider)
ConnectionProvider cp =  (((SessionFactoryImplementor) sf).getConnectionProvider());
conn = cp.getConnection();

2、获取数据库连接(org.springframework.orm.hibernate3.SessionFactoryUtils)

conn = SessionFactoryUtils.getDataSource(sf).getConnection();

3、conn = SessionFactoryUtil.getDataSource(sessionFactory).getConnection()

4、通过Session获取JDBC
session.connection();//已不推荐使用

pstmt = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);


========================================通过Session操作
1、通过new HibernateCallback(){XXX}获得的session是当前线程中的session一个回调实现能够有效地在任何Hibernate数据访问中使用。HibernateTemplate 会确保当前Hibernate的 Session 对象的正确打开和关闭,并直接参与到事务管理中去。 Template实例不仅是线程安全的,同时它也是可重用的。因而他们可以作为外部对象的实例变量而被持有。
hibernate callback分页查询
public List queryForPage(final String hql,final int offset,final int length){    
List list = getHibernateTemplate().executeFind(new HibernateCallback(){    
public Object doInHibernate(Session session) throws HibernateException,SQLException{    
Query query = session.createQuery(hql);    
query.setFirstResult(offset);    
query.setMaxResults(length);    
List list = query.list();
List lst = new ArrayList();
for(Object o : list){
DRegion r = (DRegion)o;
r.setSubCount(r.getChildRegion().size());
lst.add(r);
}
return lst;  
}
}); 
return list; 
}

2、通过this.getSession()来自于org.springframework.orm.hibernate3.SessionFactoryUtils,从当前事务或者一个新的事务中获得一个Hibernate Session,需要手动维护。

Session session = super.getSession();//事实上这里的session是通过SessionFactoryUtils创建的
Query query = session.createQuery(hql);
query.setInteger(0,id);//支持预编译的hql
List<BaseStation> bsList = query.list();//返回List
releaseSession(session);//相当于关闭Session,手动管理了

3、通过this.getHibernateTemplate().getSessionFactory().getCurrentSession()/openSession()

openSeesion():每次调用一定会新建一个Session对象。用完之后也必须调用Session类的close()方法将其关闭。

getCurrentSession():每次调用首先从上下文中查看是否有Session对象,有的话就取得当前的,没有才新建对象。使用这种方式必须在配置文件里配置当前Session的上下文:Current-Session_context_class.取值常用的有thread和jta。当执行了Transaction.commit()方法后在调用getCurrentSession()取得的也是新的对象。当事务边界要移到业务层(一个业务逻辑要调用两个不同的dao对象时)需要使用到getCurrentSession()的方法,会随着当前线程的结束而结束,不需要手动关闭。
原创粉丝点击