1. Hibernate 的主类是Session类,它提供查找,保存和删除映射对象的方法,必须来建立一个SessionFactory,来得到Session
SessionFactory 有三个重要的属性, datasource,mappingLocation,hibernateProperties
2. 直接使用Hibernate SessionFactory and Session
3. 使用Hibernate session 应该从调用beginTransaction 开始, 到调用Transaction.commit()方法结束,如果抛出异常,我们可以回滚事务
4. 两种得到Spring 实现的 HibernateTemplate 的方法
在配置文件中
5. Hibernate 不支持泛型,要对自己的代码进行单元测试和集成测试,保证返回了正确的对象
6. 如何简写DAO
省去了在每个DAO中写 sessionFactory 的麻烦
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"/>