spring持久化可以从几个方面来看:
1.对异常的处理
spring中提供了dataaccessexception,这个异常类是对现有多数据库抛出异常的封装,并可以对不同数据库抛出异常的状态码进行解释。因此,在业务层中方法声明throws dataaccessexception,可以不必担心抛出我们没有捕获到的数据库操作异常,把精力放在“业务异常”上面。
2.模板类
spring设计为了更好的管理异常、事务,避免业务方法中重复的try/catch块,设计出模板类,最重要的两个为jdbctemplate,hibernatetemplate,spring的模板类都是线程安全的,由threadlocal进行资源管理。
使用jdbctemplate,hibernatetemplate必须注入datesource,sesssionfactory,通过构造方法注入。例:
<bean id="datasource" class="org.apache.commons.dbcp.basicdatasource"
destroy-method="close">
<property name="driverclassname">
<value>${jdbc.driverclassname}</value>
</property>
<property name="url"><value>${jdbc.url}</value></property>
<property name="username"><value>${jdbc.username}</value></property>
<property name="password"><value>${jdbc.password}</value></property>
</bean>
<bean id="jdbctemplate" class="org.springframework.jdbc.core.jdbctemplate">
<constructor-org><ref bean="datasource"/></constructor-arg>
</bean>
|
hibernatetemplate配置与上相同,配置sessionfactory.把配置好的jdbctemplate,hibernatetemplate注入到我们的dao或业务类中,即可使用。但是通常我们有很多的dao类或业务类,这样做的话我们每个类都要注入一次,解决这样的问题,我们可以把模板类放到父类中,子类调用即可。
这一切,spring已经都想到了,spring提供了jdbcdaosupport,hibernatedaosupport类,这两个类都是abstract class,不能实例化,我们的业务类继承这两个类,通过getjdbctemplate(),gethibernatetemplate()方法即可得到对应的模板类。当然,我们首先要将模板类注入到这两个xxxdaosupport类中。
<bean id = "jdbcdaosupport"
class="org.springframework.jdbc.core.support.jdbcdaosupport">
<property name="jdbctemplate"><ref bean = "jdbctemplate"/></property>
</bean>
|
jdbctemplate类用法:
getjdbctemplate().query("select * from news",new rowcallbackhandler(){
public void processrow(resultset rs ){....}
}
getjdbctemplate().update(".....");
getjdbctemplate().update("update news set title=? where id=?",
new preparedstatementsetter(){
public void setvalue(preparedstatement pstmt) throws sqlexception{
pstmt.setstring("dd");
pstmt.setint(2);
}
}
gethibernatetemplate().execute(new hibernatecallback(){
public object doinhibernate)(session s) throws hibernateexception {
......
}
}
|
hibernatetemplate用法:
gethibernatetemplate().execute(new hibernatecallback(){
public object doinhibernate(session s) throws sqlexception {
return s.find("...");
}
}
|
在开发中直接使用这些模板,代码看起来可能不是很直观,本身这些模板只是为我们省了一些异常处理等代码,只是对原有hibernate session,jdbc connection,datasource的一个封装。所以,在实际开发中,为了灵活的使用模板,并充分发挥原有session等功能,还要封装一个basedao类,把常用crud、分页等操作封装供子类dao调用。