是该抛弃Spring HibernateTemplate的时候了

在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来解决。让我们来看一些代码片段:
配置文件片段:

<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>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值