• 21-Spring与Hibernate结合使用


    目录:

    1. Spring与hibernate结合关键
    2. 具体实现步骤:
      1. 导入Hibernate,Spring相关jar包
      2. UserDao中使用spring的原始代码
      3. 与spring整合,由spring创建SessionFactory对象

    1)Spring与hibernate结合关键

    • 将单例的SessionFactory对象注入Spring的IOC容器
    • 使用Spring来实现声明式事务管理

    2)具体实现步骤:

    1. 导入Hibernate,Spring相关jar包
      1. hibernate相关jar包
      2. spring core相关jar包
      3. spring aop相关jar包
      4. spring orm相关jar包:
        • spring-jdbc-3.2.5.RELEASE.jar
        • spring-orm-3.2.5.RELEASE.jar
        • spring-tx-3.2.5.RELEASE.jar
    2. UserDao中不使用spring的原始代码
      public void save(User user){
              //不使用spring的原始代码
              Configuration config = new Configuration();
              config.configure();
              SessionFactory sf = config.buildSessionFactory();
              Session session = sf.getCurrentSession();
              session.beginTransaction();
              session.save(user);
              session.getTransaction().commit();
          }
    3. 与spring整合,由spring创建SessionFactory对象:
      • 在Spring中,我们要通过Spring的某一个Hibernate Session工厂bean来获取Hibernate SessionFactory。Spring提供了多种Session工厂bean供选择,大致分为为:
        • org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
        • org.springframework.orm.hibernate5.LocalSessionFactoryBean
        • org.springframework.orm.hibernate5.LocalSessionFactoryBuilder
      1. 方式一:直接加载hibernate.cfg.xml,创建SessionFactory对象
      2. 方式二:连接池交给spring管理,其他配置还是写到hibernate.cfg.xml中
        <bean id="sessionFactory"
                class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
                <property name="dataSource" ref="dataSource"></property>
                <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
            </bean>
      3. 方式3:(推荐) 所有的配置都在spring中完成
        <?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:p="http://www.springframework.org/schema/p"
            xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
            xmlns:aop="http://www.springframework.org/schema/aop"
            xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                http://www.springframework.org/schema/beans/spring-beans.xsd
                                http://www.springframework.org/schema/context 
                                http://www.springframework.org/schema/context/spring-context-4.3.xsd
                                http://www.springframework.org/schema/aop
                                http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                                http://www.springframework.org/schema/tx 
                                http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
            
                <!-- 示例化连接池 -->
            <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
                <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/javaweb"></property>
                <property name="username" value="root"></property>
                <property name="password" value=""></property>
                <property name="initialSize" value="6"></property>
                <property name="maxActive" value="2"></property>
            </bean>
            
            <!-- spring创建SessionFactory对象 -->
            <bean id="sessionFactory"
                class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        
                <property name="dataSource" ref="dataSource"></property>
                <property name="hibernateProperties">
                    <props>
                        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop>
                            <prop key="hibernate.show_sql">true</prop>
                            <prop key="hibernate.hbm2ddl.auto">update</prop>
                        </props>
                </property>
        
                <property name="mappingLocations">
                        <list>
                            <value>classpath:claire/entity/User.hbm.xml</value>
                        </list>
                </property>
            </bean>
            
            <bean id="userDao" class="claire.dao.UserDao">
                <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>
            <bean id="userService" class="claire.service.UserService">
                <property name="userDao" ref="userDao"></property>
            </bean>
        
            <!-- spring增加对事务支持 -->
            <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
                <property name="sessionFactory" ref="sessionFactory"></property>
            </bean>
            <tx:advice id="txAdvice" transaction-manager="txManager">
                <tx:attributes>
                    <tx:method name="*" read-only="false"/>
                </tx:attributes>
            </tx:advice>
            <!-- 配置切面 -->
            <aop:config>
                <aop:advisor advice-ref="txAdvice" pointcut="execution(* claire..*Service.*(..))"/>
            </aop:config>
        </beans>

        spring整合后的代码:

        package claire.dao;
        
        import org.hibernate.SessionFactory;
        import claire.entity.User;
        
        public class UserDao {
            
            //接收spring 的Session对象
            private SessionFactory sessionFactory;
            
            public void save(User user){
                sessionFactory.getCurrentSession().save(user);
            }
        
            public void setSessionFactory(SessionFactory sessionFactory) {
                this.sessionFactory = sessionFactory;
            }
            
        }
        UserDao
    4. 之后可以选择两种方式操作:
      1. 直接在dao中使用sessionFactory对象操作数据库

            public void save(User user){
                sessionFactory.getCurrentSession().save(user);
            }
      2.  使用Spring提供的 HibernateTemplate 工具类操作数据库(5.x已经弃用了)
                HibernateTemplate hibernateTemplate = new HibernateTemplate(sessionFactory);
                hibernateTemplate.save(user);
        )
  • 相关阅读:
    JAVA面试题
    Oracle入门笔记 ——启动进阶
    SQL 基础
    BZOJ 1507 Editor(块状链表)
    BZOJ 1018 堵塞的交通traffic(线段树)
    SPOJ 422 Transposing is Even More Fun(polay计数)
    BZOJ 2754 喵星球上的点名(后缀数组)
    POJ 1568 Find the Winning Move(极大极小搜索)
    Miller-Rabin素数测试学习小计
    Lucas定理学习小记
  • 原文地址:https://www.cnblogs.com/clairexxx/p/10497646.html
Copyright © 2020-2023  润新知