Spring与Hibernate整合

本文介绍如何将Spring框架与Hibernate ORM工具进行整合,包括配置步骤、关键代码示例及事务管理等核心内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring与Hibernate进行整合

  • 加入Hibernate相关jar包
  • 加入Spring相关jar包
  • 配置Spring-hibernate.xml文件
  • 配置时应注意Hibernate版本(3、4、5)
<?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: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-4.3.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 开启注解扫描 -->    
    <context:component-scan base-package="xxxxxxxxxxx"></context:component-scan>

    <!-- 数据源配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///hibernate_demo"></property>
        <!-- 配置数据库用户名、密码 -->
        <property name="user" value="xxxxxx"></property>
        <property name="password" value="xxxxxx"></property>
        <property name="initialPoolSize" value="3"></property>
        <property name="maxPoolSize" value="10"></property>
        <property name="maxStatements" value="100"></property>
        <property name="acquireIncrement" value="2"></property>
    </bean>

    <!-- ###########Spring与Hibernate整合  hibernate配置########### -->

    <!-- 方式(1)直接加载hibernate.cfg.xml文件的方式整合
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
    </bean>    -->

    <!-- 方式(2)连接池交给spring管理  【一部分配置写到hibernate中,一份分在spring中完成】 
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
    </bean> -->

    <!-- 【推荐】方式(3)所有的配置全部都在Spring配置文件中完成(此时不需要hibernate.cfg.xml配置文件) -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!-- 注入连接池对象 -->
        <property name="dataSource" ref="dataSource"></property>

        <!-- hibernate常用配置 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

        <!-- hibernate映射配置   读取配置文件
        <property name="mappingLocations">
            <list>
                <value>classpath:cn/itcast/entity/*.hbm.xml</value>
            </list>
        </property>
        --> 
        <!-- hibernate映射配置   设置配置文件目录 -->
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:cn/itcast/entity/</value>
            </list>
        </property>
    </bean>

    <!-- ###########Spring与Hibernate整合 事务配置########### -->

    <!-- 配置Spring声明式事务 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean> 
    <!-- 配置事务事务属性 -->
     <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置事务切点,并把切点和事务属性关联起来 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.demo.ssm.serviceImpl.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans>
  • hibernate.cfg.xml相关配置
<!--如果通过导入hibernate.cfg.xml文件来进行配置-->
-----------------------------hibernate.cfg.xml----------------------------------
<!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节点代表一个数据库 -->
    <session-factory>

        <!-- 1. 数据库连接配置 -->
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql:///hibernate_demo</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">Zh86278789</property>
        <!-- 
            数据库方法配置, hibernate在运行的时候,会根据不同的方言生成符合当前数据库语法的sql
         -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- 2. 其他相关配置 -->
        <!-- 2.1 显示hibernate在运行时候执行的sql语句 -->
        <property name="hibernate.show_sql">true</property>
        <!-- 2.2 格式化sql
        <property name="hibernate.format_sql">true</property>  -->
        <!-- 2.3 自动建表  -->
        <property name="hibernate.hbm2ddl.auto">update</property>


        <!-- 配置session的创建方式:线程方式创建session对象 -->
        <property name="hibernate.current_session_context_class">thread</property>

        <!--****************** 【连接池配置】****************** -->
        <!-- 配置连接驱动管理类 -->
        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <!-- 配置连接池参数信息 -->
        <property name="hibernate.c3p0.min_size">2</property>
        <property name="hibernate.c3p0.max_size">4</property>
        <property name="hibernate.c3p0.timeout">5000</property>
        <property name="hibernate.c3p0.max_statements">10</property>
        <property name="hibernate.c3p0.idle_test_period">30000</property>
        <property name="hibernate.c3p0.acquire_increment">2</property>

        <!--****************** 【二级缓存配置】****************** -->
        <!-- a.  开启二级缓存 -->
        <property name="hibernate.cache.use_second_level_cache">true</property>
        <!-- b. 指定使用哪一个缓存框架(默认提供的) -->
        <property name="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
        <!-- 开启查询缓存 -->
        <property name="hibernate.cache.use_query_cache">true</property>
        <!-- c. 指定哪一些类,需要加入二级缓存 -->
        <class-cache usage="read-write" class="cn.itcast.b_second_cache.Dept"/>
        <class-cache usage="read-only" class="cn.itcast.b_second_cache.Employee"/>
        <!-- 集合缓存[集合缓存的元素对象,也加加入二级缓存] -->
        <collection-cache usage="read-write" collection="cn.itcast.b_second_cache.Dept.emps"/>


        <!-- 3. 加载所有映射 
        <mapping resource="cn/itcast/a_hello/Employee.hbm.xml"/>
        -->
    </session-factory>
</hibernate-configuration>
  • 实体类UserDao
import java.util.List;  

import org.hibernate.Query;  
import org.hibernate.SessionFactory;  

import com.entity.User;  

//利用注解标识持久层,并且将SessionFactiory自动注入
@Repository  
public class UserDAO implements IUserDAO  {  
    @AutoWired
    private SessionFactory sessionFactory;  

    public void setSessionFactory(SessionFactory sessionFactory) {  
        this.sessionFactory = sessionFactory;  
    }  

    @Override  

    public void addUser(User user) {//添加用户  
        sessionFactory.getCurrentSession().save(user);  
    }  

    @Override  
        public List<User> getAllUser() {//查找所有用户信息  
        String hql = "from User";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  

        return query.list();  
    }  

    @Override  
    public boolean delUser(String id) {//删除用户  
        String hql = "delete User u where u.id=?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        query.setString(0, id);  

        return (query.executeUpdate() > 0);  
    }  

    @Override  
    public User getUser(String id) {//根据id得到单个用户  
        String hql = "from User u where u.id=?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);//此时使用的是hql语句  
        query.setString(0, id);  

        return (User) query.uniqueResult();  
    }  

    @Override  
    public boolean updateUser(User user) {//修改用户信息,hql语句  
        String hql = "update User u set u.userName=?,u.age=? where u.id=?";  
        Query query = sessionFactory.getCurrentSession().createQuery(hql);  
        query.setString(0, user.getUserName());  
        query.setString(1, user.getAge());  
        query.setString(2, user.getId());  

        return (query.executeUpdate() > 0);  
    }  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值