Spring视频学习(十一)整合Hibernate3.2
1.整合的jar包
Spring2.5+Hibernate3.3+Struts1.3整合开发
hibernate核心安装包下的:
hibernate3.jar
lib\required\*.jar
lib\optional\ehcache-1.2.3.jar
hibernate 注解安装包下的
lib\test\slf4j-log4j12.jar
Spring安装包下的
dist\spring.jar
dist\modules\spring-webmvc-struts.jar
lib\jakarta-commons\commons-logging.jar、commons-dbcp.jar、commons-pool.jar
lib\aspectj\aspectjweaver.jar、aspectjrt.jar
lib\cglib\cglib-nodep-2.1_3.jar
lib\j2ee\common-annotations.jar
lib\log4j\log4j-1.2.15.jar
Struts
下载struts-1.3.8-lib.zip,需要使用到解压目录下的所有jar,建议把jstl-1.0.2.jar和standard-1.0.2.jar更换为1.1版本。Spring中已经存在一个antlr-2.7.6.jar,所以把struts中的antlr-2.7.2.jar删除,避免jar冲突。
数据库驱动jar
先整合Spring和Hibernate,测试好了再整合Struts。
2.新建项目
配置spring的xml文件,将sessionFactory由spring管理,配置spring管理hiberante的事务:
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="root"/> <property name="password" value=""/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 配置hibernate的sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"><ref bean="dataSource" /></property> <property name="mappingResources"> <list> <value>com/persia/model/Person.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.hbm2ddl.auto=update hibernate.show_sql=false hibernate.format_sql=false hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=false hibernate.cache.provider_class=org.hibernate.cache.EhCacheProvider </value> </property> </bean> <!-- 配置spring针对hibernate的事务管理器 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- 配置使用注解的方式来使用事务 --> <tx:annotation-driven transaction-manager="txManager"/> <!-- 使用手工配置的注解方式来注入bean --> <context:annotation-config></context:annotation-config> <!--定义要注入的业务bean --> <bean id="personService" class="com.persia.service.impl.PersonServiceImpl"></bean> </beans>
其中,person的hibernate配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.persia.model"> <class name="Person" table="person"> <!-- cache usage="read-write" region="com.persia.model.Person"/>--> <id name="id"> <generator class="native"/> </id> <property name="name" length="30" not-null="true"/> </class> </hibernate-mapping>
3.编写业务bean:
import java.util.List; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.persia.model.Person; import com.persia.service.IPersonService; @Transactional public class PersonServiceImpl implements IPersonService { @Resource private SessionFactory sessionFactory; public void save(Person person){ //得到spring容器管理的session.在方法执行前打开事务,结束时关闭事务。 sessionFactory.getCurrentSession().persist(person); } public void update(Person person){ //用于把游离的更新同步到数据库 sessionFactory.getCurrentSession().merge(person); } public void delete(Integer id){ sessionFactory.getCurrentSession().delete( //无需装载数据,效率高 sessionFactory.getCurrentSession().load(Person.class, id) ); } @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public Person getPerson(Integer id){ return (Person) sessionFactory.getCurrentSession().get(Person.class, id); } @SuppressWarnings("unchecked") @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true) public List<Person> getPersons(){ return sessionFactory.getCurrentSession().createQuery("from Person").list(); } }
其中使用注解配置事务,然后使用注解配置spring的依赖注入。
对于读取操作配置无不需要事务,并且配置级别为只读。
4.对业务bean进行junit测试:
package junit.test; import static org.junit.Assert.*; import java.util.List; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.persia.model.Person; import com.persia.service.IPersonService; public class IPersonServiceTest { private static IPersonService ps; @BeforeClass public static void setUpBeforeClass() throws Exception { try { ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); ps=(IPersonService) ctx.getBean("personService"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } //@Test public void testSave() { ps.save(new Person("hello")); } //@Test public void testUpdate() { Person p=ps.getPerson(5); p.setName("linda"); ps.update(p); } //@Test public void testGetPerson() { System.out.println(ps.getPerson(5).getName()); } @Test public void testDelete() { ps.delete(5); } //@Test public void testGetPersons() { List<Person> ls=ps.getPersons(); for(Person p:ls){ System.out.println(p.getName()); } } }
至此,spring和hiberante的集成已经完成。