• spring与hibernate整合


    spring2.5+hibernate3.3整合:

    jar包:

    hibsrnate核心包下:
    hibernate3.jar
    lib/required/*.jar
    lib/optional/ehcache-1.2.3.jar
    hibernate注解包下的lib/test/slf4j12.jar


    spring安装包下的
    dist/spring.jar
    dist/modules/spring-webmvc-struts.jar
    lib/jakarta-commons/commons-logging.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

    第一步

    导入jar包,spring有关包,hibernate有关包,数据库有关包。

    第二步

    编写beans.xml配置文件

    装载数据源:

    <context:property-placeholder location="classpath:jdbc.properties"/>  
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClassName}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
            <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
            <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
            <property name="maxIdleTime" value="${jdbc.maxIdleTime}"/>
            <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
        </bean>       
        

    注册sessionFactory:

      <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mappingResources">
                <list>
                    <value>cn/itcast/domain/Person.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                    hibernate.hbm2ddl.auto=update
                    hibernate.show_sql=true
                </value>
            </property>
        </bean>

    sessionFactory中mappingResources加载映射文件,hibernateProperties属性配置hibernate一些配置属性,dataSource属性配置数据源

    如果spring需要使用二级缓存的话,将二级缓存的cfg.xml中的信息也放在hibernateProperties的value属性中。

    springframework还提供了OpenSessionInView过滤器,我们可以自行配置用于hibernate开发。例子:

       
      <!-- spring的openSessionInView过滤器 -->
      <filter>
          <filter-name>openSessionInView</filter-name>
          <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>openSessionInView</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

    注册事务管理器(使用的是spring的hibernate事务管理器):

    <!-- 注册事务管理器 -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>

    beans.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:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           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/aop
               http://www.springframework.org/schema/aop/spring-aop-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/tx
               http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
               
        <context:component-scan base-package="cn.itcast"/>
             
        <context:property-placeholder location="classpath:jdbc.properties"/>  
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClassName}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
            <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
            <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
            <property name="maxIdleTime" value="${jdbc.maxIdleTime}"/>
            <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
        </bean>       
        
        <!-- 定义sessionFactory对象 -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mappingResources">
                <list>
                    <value>cn/itcast/domain/Person.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                    hibernate.hbm2ddl.auto=update
                    hibernate.show_sql=true
                </value>
            </property>
        </bean>
        
        <!-- 注册事务管理器 -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
        
        <!-- 注解管理事务 -->
        <tx:annotation-driven transaction-manager="txManager"/>
        
    </beans>
    View Code

    剩下的代码和普通的hibernate开发,普通的spring开发差不多了。

    使用sessionFactory操作数据库:

    @Transactional @Service("personService")
    public class PersonServiceBean implements PersonService {
        
        @Resource(name="sessionFactory")
        private SessionFactory sessionFactory;
        
        public void save(Person person){
            //spring会自动帮我们管理session
            sessionFactory.getCurrentSession().persist(person);
        }

    注意:

      使用sessionFactory操作数据库,sessionFactory的getCurrentSession()方法得到Session,而不是使用openSession()方法,因为spring自动帮我们管理session。

      操作方法可以使用persisit()和merge方法替代save()和update(),表现更好点罢了!

    至于hibernate映射文件等其他和前面没什么区别。

    完整代码:

      

    package cn.itcast.domain;
    
    public class Person {
        private Integer id;
        private String name;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
        public Person() {
            super();
        }
        
        public Person(Integer id, String name) {
            super();
            this.id = id;
            this.name = name;
        }
        public Person( String name) {
            super();
            this.name = name;
        }
        
        
    
    }
    Person.java
    <?xml version="1.0"?>
    <!DOCTYPE hibernate-mapping PUBLIC
          "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
              "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
    <hibernate-mapping package="cn.itcast.domain">
        <class name="Person" table="person">
            <id name="id" type="integer">
                <generator class="native"/>
            </id>
            <property name="name" not-null="true"/>
        </class>
    
    </hibernate-mapping>
    Person.hbm.xml
    package cn.itcast.service;
    
    import java.util.List;
    
    import cn.itcast.domain.Person;
    
    public interface PersonService {
    
        public abstract void save(Person person);
    
        public abstract void update(Person person);
    
        public abstract Person getPerson(Integer personId);
    
        public abstract void delete(Integer personId);
    
        public abstract List<Person> getPersons();
    
    }
    PersonService.java
    package cn.itcast.service.impl;
    
    import java.util.List;
    
    import javax.annotation.Resource;
    
    import org.hibernate.SessionFactory;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Propagation;
    import org.springframework.transaction.annotation.Transactional;
    
    import cn.itcast.domain.Person;
    import cn.itcast.service.PersonService;
    @Transactional @Service("personService")
    public class PersonServiceBean implements PersonService {
        
        @Resource(name="sessionFactory")
        private SessionFactory sessionFactory;
        
        public void save(Person person){
            //spring会自动帮我们管理session
            sessionFactory.getCurrentSession().persist(person);
        }
        
        public void update(Person person){
            sessionFactory.getCurrentSession().merge(person);
        }
        
        @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
        public Person getPerson(Integer personId){
            return (Person) sessionFactory.getCurrentSession().get(Person.class, personId);
        }
        
        public void delete(Integer personId){
            sessionFactory.getCurrentSession().delete(
                    sessionFactory.getCurrentSession().load(Person.class, personId));
        }
        
        @SuppressWarnings("unchecked") @Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
        public List<Person> getPersons(){
            return sessionFactory.getCurrentSession().createQuery("from Person").list();
            
        }
    }
    PersonServiceBean
    package junit.test;
    
    
    import java.util.List;
    
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import cn.itcast.domain.Person;
    import cn.itcast.service.PersonService;
    
    public class PersonServiceTest {
        private static PersonService personService;
    
        @BeforeClass
        public static void setUpBeforeClass() throws Exception {
            try{
                ApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
                personService=(PersonService) ctx.getBean("personService");
            }catch(RuntimeException e){
                e.printStackTrace();
            }
        }
        
        @Test public void testSave(){
            personService.save(new Person("小张"));
        }
        @Test public void testDetete(){
            personService.delete(1);
        }
        @Test public void testUpdate(){
            Person person=personService.getPerson(1);
            person.setName("小丽");
            personService.update(person);
        }
        @Test public void testGetPerson(){
            Person person=personService.getPerson(1);
            System.out.println(person.getName());
        }
        @Test public void testGetPersons(){
            List<Person> persons=personService.getPersons();
            for(Person p:persons){
                System.out.println(p.getName()+"--"+p.getId());
            }
        }
    
    }
    PersonServiceTest
    <?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:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           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/aop
               http://www.springframework.org/schema/aop/spring-aop-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/tx
               http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
               
        <context:component-scan base-package="cn.itcast"/>
             
        <context:property-placeholder location="classpath:jdbc.properties"/>  
        
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClassName}"/>
            <property name="jdbcUrl" value="${jdbc.url}"/>
            <property name="user" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
            <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
            <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
            <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
            <property name="maxIdleTime" value="${jdbc.maxIdleTime}"/>
            <property name="acquireIncrement" value="${jdbc.acquireIncrement}"/>
        </bean>       
        
        <!-- 定义sessionFactory对象 -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mappingResources">
                <list>
                    <value>cn/itcast/domain/Person.hbm.xml</value>
                </list>
            </property>
            <property name="hibernateProperties">
                <value>
                    hibernate.dialect=org.hibernate.dialect.MySQLDialect
                    hibernate.hbm2ddl.auto=update
                    hibernate.show_sql=true
                </value>
            </property>
        </bean>
        
        <!-- 注册事务管理器 -->
        <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory"/>
        </bean>
        
        <!-- 注解管理事务 -->
        <tx:annotation-driven transaction-manager="txManager"/>
        
    </beans>
    beans.xml
    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/customers?useUnicode=true&characterEncoding=UTF-8
    jdbc.username=guodaxia
    jdbc.password=961012gz
    jdbc.maxPoolSize=100
    jdbc.minPoolSize=10
    jdbc.initialPoolSize=20
    jdbc.maxIdleTime=600
    jdbc.acquireIncrement=5
    jdbc.properties

    jar:

    jar不敢保证,但是其他配置大概就是这样了。

  • 相关阅读:
    lucene教程【转】【补】
    线程本地变量ThreadLocal (耗时工具)【原】
    Exception异常转String【转】
    织梦DedeCms网站更换域名后文章图片路径批量修改
    织梦DedeCms去掉栏目页面包屑导航最后的分隔符“>”
    dedecms网站栏目增加缩略图的方法-测试通过
    织梦dedecms调用子栏目的方法
    织梦DedeCMS调用二级子栏目或者多级栏目解决方法
    dedecms首页调用栏目内容和单页内容的方法
    JS中的prototype
  • 原文地址:https://www.cnblogs.com/aigeileshei/p/5915882.html
Copyright © 2020-2023  润新知