(3)
时间:2012-04-26 IBM 陈雄华
但是,不使用 Hibernate 事务管理器,在 Spring 中,Hibernate 照样也可以工作,来看 下面的例子:
清单 3.UserHibernateWithoutTransManagerService.java
package user.withouttm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.apache.commons.dbcp.BasicDataSource;
import user.User;
@Service("service2")
public class UserHibernateWithoutTransManagerService {
@Autowired
private HibernateTemplate hibernateTemplate;
public void addScore(String userName,int toAdd){
User user = (User)hibernateTemplate.get(User.class,userName);
user.setScore(user.getScore()+toAdd);
hibernateTemplate.update(user);
}
public static void main(String[] args) {
//参考UserJdbcWithoutTransManagerService相应代码
…
}
}
此时,采用 hiberWithoutTransManager.xml 的配置文件,其配置内容如下:
清单 4.hiberWithoutTransManager.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context- 3.0.xsd">
<!--省略掉包扫描,数据源,JdbcTemplate配置部分,参见jdbcWithoutTransManager.xml -->
…
<bean id="sessionFactory"
class=
"org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource">
<property name="annotatedClasses">
<list>
<value>user.User</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.Oracle10gDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate"
p:sessionFactory-ref="
|