Spring 集成Hibernate 并进行测试


Spring的相关配置
<? xml version = "1.0" encoding = "UTF-8" ?>
< beans xmlns = "http://www.springframework.org/schema/beans"
      xmlns:p = "http://www.springframework.org/schema/p"
    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:jdbc = "http://www.springframework.org/schema/jdbc"
    xmlns:tx = "http://www.springframework.org/schema/tx"
    xmlns:jpa = "http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"                                       
        default-lazy-init = "true" >
        <!-- 要使用注解必须添加此项 -->  
        < context:annotation-config />  
        <!-- 将com.spring.data包内的bean注入 -->
        < context:component-scan base-package = "com.spring.data" ></ context:component-scan >
        <!-- 引入外部资源文件 -->
<!--         <context:property-placeholder location="classpath:application.properties"/> -->
        < context:property-placeholder location = "classpath:application.properties" system-properties-mode = "FALLBACK" />
        <!-- 启用pringjdbc的封装 -->
        < bean id = "sessionFactory" class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean" lazy-init = "false" >
             <!-- 注入datasource,给sessionfactoryBean内setdatasource提供数据源 -->
             < property name = "dataSource" ref = "dataSource" />
             < property name = "configLocation" value = "classpath:com/spring/data/hibernate.cfg.xml" ></ property >
             <!-- 加载实体类的映射文件位置及名称 -->
             < property name = "mappingLocations" value = "classpath:com/spring/data/*.hbm.xml" ></ property >
         </ bean >  
        
        <!-- 配置数据源 -->
        < bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method = "close" >
               <!-- 数据驱动 -->
            < property name = "driverClass" >
                < value > ${jdbc.driver} </ value >
            </ property >
            <!-- 数据库连接 -->
            < property name = "jdbcUrl" >
                < value > ${jdbc.url} </ value >
            </ property >
            <!-- 数据库用户名 -->
            < property name = "user" >
                < value > ${jdbc.username} </ value >
            </ property >
            <!-- 数据库密码 -->
            < property name = "password" >
                < value > ${jdbc.password} </ value >
            </ property >
             <!--连接池中保留的最大连接数。Default: 15 -->    
            < property name = "maxPoolSize" value = "${c3p0.maxPoolSize}" />  
            <!--连接池中保留的最小连接数-->    
            < property name = "minPoolSize" value = "${c3p0.minPoolSize}" />  
            <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->   
            < property name = "initialPoolSize" value = "${c3p0.initialPoolSize}" />  
            <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->    
            < property name = "maxIdleTime" value = "${c3p0.maxIdleTime}" />  
             <!--当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出   
              SQLException,如设为0则无限期等待。单位毫秒。Default: 0 -->    
            < property name = "checkoutTimeout" value = "${c3p0.checkoutTimeout}" />
            <!--两次连接中间隔时间,单位毫秒。Default: 1000 -->    
            < property name = "acquireIncrement" value = "${c3p0.acquireIncrement}" />  
            <!--每60秒检查所有连接池中的空闲连接。Default: 0 -->    
            < property name = "idleConnectionTestPeriod" value = "${c3p0.idleConnectionTestPeriod}" />
            <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements   
                       属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。   
                       如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->    
            < property name = "maxStatements" value = "${c3p0.maxStatements}" />   
        </ bean >  
</ beans >
hibernate.cfg.xml的配置信息
<? xml version = "1.0" encoding = "UTF-8" ?>
<! DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd" >
< hibernate-configuration >
    < session-factory >
        <!-- 配置Hibernate的基本属性 -->
        <!-- 1.数据源配置到IOC容器中 -->
        <!-- 2.关联的.hbm.xml也在IOC容器配置SessionFactory实例 -->
        <!-- 3.配置Hibernate的基本属性:方言,SQL显示及格式化,生成数据表的策略以及二级缓存 -->
        < property name = "hibernate.dialect" > org.hibernate.dialect.MySQL5Dialect </ property >
        < property name = "hibernate.show_sql" > true </ property >
        <!-- 把session事务交给每次请求的线程 -->
        < property name = "hibernate.current_session_context_class" > thread </ property >
        <!-- 把session事务交给spring来管理 如果不配置的话,默认的会使该设置-->
        <!-- <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</property> -->
        <!-- 如果表不存在则hibernate进行创建 -->
        < property name = "hbm2ddl.auto" > update </ property >
    </ session-factory >
</ hibernate-configuration >
实体类的映射文件
<? 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 >
    < class name = "com.spring.data.User" table = "USER" catalog = "test" >
        < id name = "id" type = "java.lang.Integer" >
            < column name = "id" />
            < generator class = "identity" />
        </ id >
        < property name = "name" type = "java.lang.String" >
            < column name = "name" length = "32" />
        </ property >
        < property name = "address" type = "java.lang.String" >
            < column name = "address" length = "64" />
        </ property >
        < property name = "age" type = "java.lang.Integer" >
            < column name = "age" />
        </ property >
    </ class >
</ hibernate-mapping >
持久层操作数据库
@Repository
public class JdbcSpitterDao {
     
      @Autowired
      private SessionFactory sessionFactory ;
          
      /**
      * 插入数据
      */
      public void add(User user ){
          Session session = sessionFactory .getCurrentSession();
          Transaction transaction = session .beginTransaction();
           session .save( user );
           transaction .commit();
     }
      /**
      * 获取User对象
      */
      public User queryById( int id ){
          Session session = sessionFactory .getCurrentSession();
          Transaction transaction = session .beginTransaction();
          User user = (User) session .get(User. class , id );
           transaction .commit();
           return user ;
     }
      /**
      * 根据User对象进行查找
      */
      @SuppressWarnings ( "unchecked" )
      public List<User> queryByHql( int id ){
          Session session = sessionFactory .getCurrentSession();
          Transaction transaction = session .beginTransaction();
          String sql = "from User where id=" + id ;
          Query query = session .createQuery( sql );
          List<User> users = query .list();
           transaction .commit();
           return users ;
     }
      /**
      * 根据id修改user对象
      */
      public void update(User user ){
          Session session = sessionFactory .getCurrentSession();
          Transaction transaction = session .beginTransaction();
           session .update( user );
           transaction .commit();
     }
      /**
      * 根据id删除user对象
      */
      public void delete(User user ){
          Session session = sessionFactory .getCurrentSession();
          Transaction transaction = session .beginTransaction();
           session .delete( user );
           transaction .commit();
     }
}
注意事项
    //这里的每个方法的事务都交给当前线程来处理,如果使用注解来管理事务则必须将hibernate.cfg.xml中的 < property name = "hibernate.current_session_context_class" > thread </ property >修改为
     // <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</property>同事还需要在spring的配置文件中加入:
     // <!-- 设定transactionManager -->  
          // < bean id = "transactionManager" class = "org.springframework.orm.hibernate3.HibernateTransactionManager" >
      //    < property name = "sessionFactory" ref = "sessionFactory" ></ property >
      // </ bean >
      // <!--启动spring事务注解功能-->
    // < tx:annotation-driven transaction-manager = "transactionManager" />  

如果启用每个线程来管理事务也就是配置 < property name = "hibernate.current_session_context_class" > thread </ property > ,但是在持久层用了注解的话,会报如下的错误 
如果将事务交给了spring容器进行管理也就是 <property name="hibernate.current_session_context_class">org.springframework.orm.hibernate3.SpringSessionContext</property>但是在持久层每个事务还是交给当前线程进行处理的话将会报如下的错误

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

fjkxyl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值