Hibernate SessionFactory and Session

本文介绍Hibernate主类Session的使用方式,包括通过SessionFactory获取Session、事务处理、使用HibernateTemplate及简化DAO开发等内容。
1. Hibernate 的主类是Session类,它提供查找,保存和删除映射对象的方法,必须来建立一个SessionFactory,来得到Session

SessionFactory 有三个重要的属性, datasource,mappingLocation,hibernateProperties

<bena id="hibernateSessionFactory">
<property name="dataSource" ref="dataSource"/>
<property name="mappingLocations">
<list>
<value>classpath*:/com/test/*.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
......
</property>
</bean>


2. 直接使用Hibernate SessionFactory and Session

ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml");
SessionFactory sessionFactory=(SessionFactory)ac.getBean("hibernateSessionFactory");
Session session=sessionFactory.openSession();
// do your work
session.close();

3. 使用Hibernate session 应该从调用beginTransaction 开始, 到调用Transaction.commit()方法结束,如果抛出异常,我们可以回滚事务

ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml");
SessionFactory sessionFactory=(SessionFactory)ac.getBean("hibernateSessionFactory");
Session session=null;
Transaction transaction=null;
try{
session=sessionFactory.openSession();
transaction=session.beginTransaction();

// do your work
tramsactopm.commit();
}catch(Exception e){
if(transaction!=null)transaction.rollback();
throw e;
}finally{
if(session!=null) session.close();
}

4. 两种得到Spring 实现的 HibernateTemplate 的方法

ApplicationContext ac=new ClassPathXmlApplicationContext("application.xml");
SessionFactory sessionFactory=(SessionFactory)ac.getBean("hibernateSessionFactory");
HibernateTemplate template=new HibernateTemplate(sessionFactory)
template.execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
//do the work
return null
}
})

在配置文件中

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate.HibernateTemplate">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
HibernateTemplate template=(HibernateTemplate)at.getBean("hibernateTemplate");
template.execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException,SQLException{
//do the work
return null
}
})

5. Hibernate 不支持泛型,要对自己的代码进行单元测试和集成测试,保证返回了正确的对象

6. 如何简写DAO
省去了在每个DAO中写 sessionFactory 的麻烦

<bean id="hibernateDaoSupport" abstract="true" class="org.springframework.orm.hibernate.support.HibernateDaoSupport">
<property name="sessionFactory" ref="hibernateSessionFactory"/>
</bean>
<bean id="dao1" class="com.test.class1" parent="hibernateDaoSupport"/>
<bean id="dao2" class="com.test.class2" parent="hibernateDaoSupport"/>
<bean id="dao3" class="com.test.class3" parent="hibernateDaoSupport"/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值