您的位置:首页 > 编程语言 > Java开发

是该抛弃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来解决。让我们来看一些代码片段:

配置文件片段:

<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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: