是该抛弃Spring HibernateTemplate的时候了
2013-04-22 20:56
525 查看
在spring2.0之前,我们在使用hibernate和spring的时候,都会被HibernateTemplate为我们提供 benefits(资源和事务管理以及把那个“丑陋”的checked exception转换为runtime exception-DataAccessException )而折服,在项目中不由自主、不假思索地使用它和那个经典的callback方法。而如今,hibernate3.0.1+ 、spring 2.0+版本以后,我们可以在数据访问层直接使用hinberate的session API(例如SessionFactory.getCurrentSession),不并担心session和transaction
management。至于error handling可以通过spring的@Repository annotation和post processor-PersistenceExceptionTranslationPostProcessor来解决。让我们来看一些代码片段:
配置文件片段:
数据访问层代码片段:
在xml配置文件里面通过配置的post processor会自动检测@Repository标注的bean并为该bean打开exception转换功能。
如果不支持annotations,可以通过AOP来实现,更方便
management。至于error handling可以通过spring的@Repository annotation和post processor-PersistenceExceptionTranslationPostProcessor来解决。让我们来看一些代码片段:
配置文件片段:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3. LocalSessionFactoryBean"> <!-- the properties setting--> </bean> <bean id="accountRepo" class="com.mycompany.HibernateAccountRepository"> <constructor-arg ref="sessionFactory"></constructor-arg> </bean> <bean class="org.springframework.dao.annotation. PersistenceExceptionTranslationPostProcessor"/>
数据访问层代码片段:
@Repository public class HibernateAccountRepository implements AccountRepository { private SessionFactory factory; public HibernateAccountRepository(SessionFactory factory) { this.factory = factory; } public Account loadAccount(String username) { return (Account)factory.getCurrentSession() .createQuery("from Account acc where acc.name = :name") .setParameter("name", "thethirdpart").uniqueResult(); } }
在xml配置文件里面通过配置的post processor会自动检测@Repository标注的bean并为该bean打开exception转换功能。
如果不支持annotations,可以通过AOP来实现,更方便
<bean id="persistenceExceptionInterceptor" class="org.springframework.dao.support.PersistenceExceptionTranslationInterceptor"/> <aop:config> <aop:advisor pointcut="execution(* *..*Repository+.*(..))" advice-ref="persistenceExceptionInterceptor" /> </aop:config>
相关文章推荐
- 是该抛弃Spring HibernateTemplate的时候了
- hibernate+spring delete,saveorupdate,find的时候为什么报nested exception is org.hibernate.MappingException:
- Spring整合Hibernate的时候使用hibernate.cfg.xml
- Spring中常用的hql查询方法(getHibernateTemplate())
- Spring中常用的hql查询方法(getHibernateTemplate())
- spring整合hibernate,在获取sessionFactory的时候报错,求解决办法!!
- spring注解空指针异常 'sessionFactory' or 'hibernateTemplate' is required的解决方法
- 在Spring使用getHibernateTemplate().save()为何不能更新数据库
- spring+hibernate 使用getHibernateTemplate实现分页
- 懒得笔记6 spring hibernate template
- Spring中常用的hql查询方法 (getHibernateTemplate())
- spring整合hibernate时的getHibernateTemplate()异常
- Spring中常用的hql查询方法(getHibernateTemplate())
- hibernate整合spring开发的时候遇到的一些小问题
- Spring中常用的hql查询方法(getHibernateTemplate())
- Spring中常用的hql查询方法 (getHibernateTemplate())
- 对spring管理的hibernate的getHibernateTemplate的find方法整理
- Spring入门之解决HibernateTemplate.save()不能写入数据
- Spring中常用的hql查询方法(getHibernateTemplate())
- Spring中常用的hql查询方法(getHibernateTemplate())