spring 调整hibernate (3)
从JDK5.0就开始引入了注解特性,能够很方便的添加元数据,简化程序中的配置信息,之前spring整合hibernate时,都采用org.springframework.orm.hibernate3.LocalSessionFactoryBean来创建sessionfactory对象,该类是基于读取xml配置文件来创建的,那么是否也能与时俱进,采用注解的形式来进行配置呢?答案是肯定的,下面就采用基于注解的形式来整合。
在spring的orm中,我现org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
继承LocalSessionFactoryBean,所以我们可以使用该类来创建sessionFactory对象。
创建持久化类User
package com.jacksoft.spring.hibernate.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; // Entity为了声明该类是一个持久化Bean @Entity //声明该bean对应的表名以及对应的数据库名称 @Table(name="user",catalog="spring_test") public class User { //标示主键ID @Id //说明主键值为自动生成,可以根据GenerationType来指定 @GeneratedValue(generator="generator",strategy=GenerationType.AUTO) //对应的列名 @Column(name="id") private Integer id; @Column(name="username") private String username; @Column(name="password") private String password; @Column(name="levelCode") private Integer levelCode; //省略setter和getter }
定义接口IDao:
package com.jacksoft.spring.hibernate.dao; public interface IDao<T> { public void save(T t); }
定义实现类UserDao:
package com.jacksoft.spring.hibernate.dao.impl; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.jacksoft.spring.hibernate.dao.IDao; import com.jacksoft.spring.hibernate.model.User; public class UserDao extends HibernateDaoSupport implements IDao<User> { @Override public void save(User t) { getHibernateTemplate().save(t); } }
这里同样继承HibernateDaoSupport来便于获取hibernateTemplate对象
定义数据库连接信息resource.properties
driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/spring_test username=root password=hwroot
定义spring配置文件springConfig.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:aop="http://www.springframework.org/schema/aop" 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 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:resource.properties</value> </list> </property> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driverClass}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!-- 定义扫描的包,还可以定义annotatedPackages和annotatedClasses这两个属性 --> <property name="packagesToScan" value="com.jacksoft.spring.hibernate.model"/> <!-- 定义hibernate配置文件,从源码来看 该属性为properties --> <property name="hibernateProperties"> <props> <!-- 配置方言为MYSQL --> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <!-- 是否显示语句 --> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="abstractDao" abstract="true"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userDao" class="com.jacksoft.spring.hibernate.dao.impl.UserDao" parent="abstractDao"/> </beans>
当采用注解来标记时,不再需要*.hbm.xml配置文件,而是直接配置packagesToScan来扫描包下面的持久化类来达到同样的效果。
接下来就是测试类SpringHibernateAnnotationTest
package com.jacksoft.spring.hibernate.test; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.jacksoft.spring.hibernate.dao.IDao; import com.jacksoft.spring.hibernate.model.User; public class SpringHibernateAnnotationTest { @Test public void testInsert(){ ApplicationContext context = new ClassPathXmlApplicationContext("springConfig.xml"); IDao<User> dao = context.getBean("userDao", IDao.class); User user = new User(); user.setUsername("springTestAnnotation"); user.setPassword("a111"); user.setLevelCode(3); dao.save(user); } }
测试类始终没什么变化,这样我们能很好的去替换数据库的操作,而不影响其他代码,很方便。
这就是基于注解风格的基本配置,当然在配置持久化类的时候,配置还比较多,比如多对一关系,栏位长度等等,这里的注解尽量使用标准javax.persistence下面的注解,而不要使用hibernate下面的注解。
最后再为其添加上事务机制,采用声明式事务来处理,这样能达到非侵入目的,即不改变源代码的情况下,直接进行配置就可以了,这就是spring的强大
spring为我们提供了org.springframework.orm.hibernate3.HibernateTransactionManager来管理sessionFactory对象,另外还需要进行AOP配置,具体如下:
<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="save"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut expression="execution(* com.jacksoft.spring.hibernate.dao..*.*(..))" id="method"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="method"/> </aop:config>
只对save方法进行事务控制,是不是很方便呢?