首页 > 代码库 > Spring整合Hibernate

Spring整合Hibernate

1.带有hibernate.cfg.xml配置文件(不能加绑定当前线程的配置)

1.编写实体的映射文件(xx.hbm.xml)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
    
<hibernate-mapping>
    
    <class name="com.ssh.domain.Customer" table="cst_customer">
        <id name="cust_id" column="cust_id">
            <generator class="native"/>
        </id>
        
        <property name="cust_name" column="cust_name"/>
        <property name="cust_user_id" column="cust_user_id"/>
        <property name="cust_create_id" column="cust_create_id"/>
        <property name="cust_source" column="cust_source"/>
        <property name="cust_industry" column="cust_industry"/>
        <property name="cust_level" column="cust_level"/>
        <property name="cust_linkman" column="cust_linkman"/>
        <property name="cust_phone" column="cust_phone"/>
        <property name="cust_mobile" column="cust_mobile"/>
        
    </class>
    
</hibernate-mapping>  

2.将配置文件配置到hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
<hibernate-configuration>
    
    <session-factory>
        <!-- 必须配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///SSH</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">toor</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        
        <!-- 可选配置 -->
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.format_sql">true</property>
        <property name="hibernate.hbm2ddl.auto">update</property>
        
        <!-- 配置C3P0的连接池 -->
        <property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        
        <!-- 映射配置文件 -->
        <mapping resource="com/ssh/domain/Customer.hbm.xml"/>
        
    </session-factory>
    
</hibernate-configuration>    

3.在applicationContext.xml中配置hibernate.cfg.xml

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"/>
    </bean>

4.编写DAO层,继承(HibernateDaoSupport)

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

    /**
     * 保存客户
     */
    @Override
    public void save(Customer customer) {
        System.out.println("持久层:保存客户...");
        this.getHibernateTemplate().save(customer);
    }

}

4.1将dao注入service

    private CustomerDao customerDao;
    public void setCustomerDao(CustomerDao customerDao) {
        this.customerDao = customerDao;
    }
    <bean id="customerService" class="com.ssh.service.CustomerServiceImpl">
        <property name="customerDao" ref="customerDao"/>
    </bean>

5.Spring管理dao

    <bean id="customerDao" class="com.ssh.dao.CustomerDaoImpl">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

6.开启事务配置

6.1开启平台事务管理器

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

6.2开启注解事务

    <tx:annotation-driven transaction-manager="transactionManager"/>

6.3在service类上添加注释

技术分享

2.不带有hibernate.cfg.xml配置文件

 在上面的基础上将hibernate.cfg.xml中的配置转移到applicationContext.xml

1.配置连接池

    <!-- 配置C3P0连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///SSH"/>
        <property name="user" value="root"/>
        <property name="password" value="toor"/>
    </bean>    

2.修改LocalSessionFactoryBean

删除:

<property name="configLocation" value="classpath:hibernate.cfg.xml"/>

添加:

    <!-- LocalSessionFactoryBean加载配置文件 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 加载连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 加载方言,加载可选 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        
        <!-- 引入映射的配置文件 -->
        <property name="mappingResources">
            <list>
                <value>com/ssh/domain/Customer.hbm.xml</value>
            </list>
        </property>
    </bean>

3.删除hibernate.cfg.xml

3.Hibernate模板类的常用方法

1.添加

    public void save(Customer customer) {
        this.getHibernateTemplate().save(customer);
    }

2.修改

    public void update(Customer customer) {
        this.getHibernateTemplate().update(customer);
    }

3.删除

    public void delete(Customer customer) {
        this.getHibernateTemplate().delete(customer);
    }

4.查询一条记录

    public Customer get(Customer customer) {
        return this.getHibernateTemplate().get(Customer.class, customer.getCust_id());
    }

5.查询多条记录(HQL方式)

    public List<Customer> findAllByHQL() {
        List<Customer> list = (List<Customer>) this.getHibernateTemplate().find("from Customer");
        return list;
    }

6.查询多条记录(QBC方式)

    public List<Customer> findAllByQBC() {
        DetachedCriteria criteria = DetachedCriteria.forClass(Customer.class);
        List<Customer> list = (List<Customer>) this.getHibernateTemplate().findByCriteria(criteria);
        return list;
    }

4.延迟加载问题

1. 使用延迟加载的时候,再WEB层查询对象的时候程序会抛出异常!
    * 原因是延迟加载还没有发生SQL语句,在业务层session对象就已经销毁了,所以查询到的JavaBean对象已经变成了托管态对象!
    * 注意:一定要先删除javassist-3.11.0.GA.jar包(jar包冲突了)

2. 解决办法非常简单,Spring框架提供了一个过滤器,让session对象在WEB层就创建,在WEB层销毁。只需要配置该过滤器即可
    * 但是:要注意需要在struts2的核心过滤器之前进行配置
        <filter>
            <filter-name>OpenSessionInViewFilter</filter-name>
            <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>OpenSessionInViewFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

Spring整合Hibernate