zoukankan      html  css  js  c++  java
  • spring整合mybatis(hibernate)配置

    一、Spring整合配置Mybatis

      spring整合mybatis可以不需要mybatis-config.xml配置文件,直接通过spring配置文件一步到位。一般需要具备如下几个基本配置。

      1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置)

     1    <!-- 导入properties配置文件 -->
     2     <context:property-placeholder location="classpath*:/jdbc.properties"/>
     3 
     4     <!-- 数据源基本配置 -->
     5     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     6          <property name="username" value="${jdbc.username}"/>
     7          <property name="password" value="${jdbc.password}"/>
     8          <property name="url" value="${jdbc.url}"/>
     9          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    10     </bean>

       我们将参数配置统一写入jdbc.properties文件中:

    1 jdbc.url=jdbc:mysql://localhost:3306/mydb
    2 jdbc.driverClassName=com.mysql.jdbc.Driver
    3 jdbc.username=root
    4 jdbc.password=root

      2.配置SessionFactory(用于将数据源和mybatis的mapper映射文件进行管理和初始化)

    1    <!-- 创建sessionFactory -->
    2     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    3         <property name="dataSource" ref="dataSource"/>
    4         <!-- 扫描mapper映射文件 -->
    5         <property name="mapperLocations" value="classpath*:dao/mapping/*.xml" />
    6     </bean>

      3.扫描mapper映射文件所对应的dao接口类(其实dao接口的是实现类就是mapper.xml映射文件,此配置是为了将接口和映射文件进行初始化)

    1    <!-- 扫描与mapper映射文件对应的dao接口类 -->
    2     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    3         <property name="basePackage" value="dao.daoInterface"/>
    4         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    5     </bean>

      4.创建事务(事务有两种配置方式:注解方式和aop切入方式)

    1   <!-- 创建事务管理 -->
    2     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    3         <property name="dataSource" ref="dataSource"/>
    4     </bean>

      创建好事务管理后,我们可以选择使用注解方式实现管理,或者aop织入管理

        4.1注解方式

    1 <!-- 注解式事务配置,启动事务注解驱动 -->
    2 <tx:annotation-driven/>

        注解配置方式要先通过配置文件启动事务注解驱动,然后在要加事务的方法上面加上事务注解:@Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED) 事务相关知识可参考http://www.cnblogs.com/caijh/p/7724964.html

    1   @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.READ_COMMITTED)
    2     @Override
    3     public void insertUser(UserEntity userEntity) {
    4         for(int i=0;i<10;i++){
    5             userEntity.setId(111+i);
    6             userEntity.setUsername("mybatis "+i);
    7             userDao.insertUser(userEntity);
    8         }
    9     }

        4.2 AOP织入方式

     1 <!-- aop切入式事务配置 -->
     2     <tx:advice id="trAdvice" transaction-manager="transactionManager">
     3         <tx:attributes>
     4             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
     5         </tx:attributes>
     6     </tx:advice>
     7 
     8     <aop:config>
     9         <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/>
    10         <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/>
    11     </aop:config>

      AOP相关知识可参考:http://www.cnblogs.com/caijh/p/7710725.html

    最终配置如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--
     3   ~ @(#) applicationContext.xml
     4   ~ <br> Copyright:  Copyright (c) 2017
     5   ~ <br> @author cjh
     6   ~ <br> 2017-10-29 15:45:16
     7   -->
     8 <beans xmlns="http://www.springframework.org/schema/beans"
     9        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    10        xmlns:tx="http://www.springframework.org/schema/tx"
    11        xmlns:aop="http://www.springframework.org/schema/aop"
    12        xmlns:context="http://www.springframework.org/schema/context"
    13        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    14        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    15        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.3.xsd
    16        http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">
    17 
    18     <!-- 导入properties配置文件 -->
    19     <context:property-placeholder location="classpath*:/jdbc.properties"/>
    20 
    21     <!-- 扫描注解包 -->
    22     <context:component-scan base-package="dao.daoInterface"/>
    23     <context:component-scan base-package="service.serviceImpl" />
    24 
    25     <!-- 数据源基本配置 -->
    26     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    27          <property name="username" value="${jdbc.username}"/>
    28          <property name="password" value="${jdbc.password}"/>
    29          <property name="url" value="${jdbc.url}"/>
    30          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    31     </bean>
    32 
    33     <!-- 创建sessionFactory -->
    34     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    35         <property name="dataSource" ref="dataSource"/>
    36         <!-- 扫描mapper映射文件 -->
    37         <property name="mapperLocations" value="classpath*:dao/mapping/*.xml" />
    38     </bean>
    39 
    40     <!-- 扫描与mapper映射文件对应的dao接口类 -->
    41     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    42         <property name="basePackage" value="dao.daoInterface"/>
    43         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    44     </bean>
    45 
    46 
    47     <!-- 创建事务管理 -->
    48     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    49         <property name="dataSource" ref="dataSource"/>
    50     </bean>
    51 
    52     <!-- 注解式事务配置,启动事务注解驱动 -->
    53     <!--<tx:annotation-driven/>-->
    54 
    55     <!-- aop切入式事务配置 -->
    56     <tx:advice id="trAdvice" transaction-manager="transactionManager">
    57         <tx:attributes>
    58             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED"/>
    59         </tx:attributes>
    60     </tx:advice>
    61 
    62     <aop:config>
    63         <aop:pointcut id="serviceAdvice" expression="execution(* service.serviceImpl.*.*(..))"/>
    64         <aop:advisor advice-ref="trAdvice" pointcut-ref="serviceAdvice"/>
    65     </aop:config>
    66 
    67 </beans>
    View Code

       SSMDemo整合配置源码位置:https://gitee.com/codecaijh/SSMDemo

     二、Spring整合配置Hibernate

      Spring整合配置hibernate和Mybatis的配置大同小异,主要区别在与SessionFactory和映射文件的管理配置,但目的都是一样的。

      1.配置数据源(连接数据库最基本的属性配置,如数据库url,账号,密码,和数据库驱动等最基本参数配置)【同Mybatis配置】

      2.配置SessionFactory(因为Hibernate对数据库操作做了封装,所以需要一些额外的属性配置)

     1 <!-- 创建sessionFactory -->
     2     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
     3         <property name="dataSource" ref="dataSource"/>
     4         <property name="hibernateProperties">
     5             <props>
     6                 <prop key="hibernate.show_sql">true</prop>
     7                 <prop key="hibernate.format_sql">true</prop>
     8                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
     9                 <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
    10             </props>
    11         </property>
    12         <!-- 实体类映射文件 -->
    13         <property name="mappingLocations">
    14             <list>
    15                 <value>classpath*:/domain/*.hbm.xml</value>
    16             </list>
    17         </property>
    18         <!-- 扫描实体类包 -->
    19         <property name="packagesToScan">
    20             <value>domain</value>
    21         </property>
    22         <!-- 实体类 -->
    23         <property name="annotatedClasses">
    24             <list>
    25                 <value>domain.UserEntity</value>
    26             </list>
    27         </property>
    28     </bean>

      Hibernate的配置中,把映射文件和是实体类映射全部配置在SessionFactory中,也就是和Mybatis第2步和第3步类似,

      3.创建事务(事务有两种配置方式:注解方式和aop切入方式)【同Mybatis配置】

      最终配置如下:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!--
     3   ~ @(#) applicationContext.xml
     4   ~ <br> Copyright:  Copyright (c) 2017
     5   ~ <br> @author cjh
     6   ~ <br> 2017-10-29 15:45:16
     7   -->
     8 <beans xmlns="http://www.springframework.org/schema/beans"
     9        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    10        xmlns:tx="http://www.springframework.org/schema/tx"
    11        xmlns:aop="http://www.springframework.org/schema/aop"
    12        xmlns:context="http://www.springframework.org/schema/context"
    13        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    14        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
    15        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    16        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.3.xsd">
    17 
    18     <!-- 导入properties配置文件 -->
    19     <context:property-placeholder location="classpath*:/jdbc.properties"/>
    20 
    21     <!-- 扫描注解包 -->
    22     <context:component-scan base-package="dao.daoImpl"/>
    23     <context:component-scan base-package="service.serviceImpl" />
    24 
    25     <!-- 数据源基本配置 -->
    26     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    27          <property name="username" value="${jdbc.username}"/>
    28          <property name="password" value="${jdbc.password}"/>
    29          <property name="url" value="${jdbc.url}"/>
    30          <property name="driverClassName" value="${jdbc.driverClassName}"/>
    31     </bean>
    32 
    33     <!-- 创建sessionFactory -->
    34     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    35         <property name="dataSource" ref="dataSource"/>
    36         <property name="hibernateProperties">
    37             <props>
    38                 <prop key="hibernate.show_sql">true</prop>
    39                 <prop key="hibernate.format_sql">true</prop>
    40                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    41                 <!--<prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</prop>-->
    42             </props>
    43         </property>
    44         <!-- 实体类映射文件 -->
    45         <property name="mappingLocations">
    46             <list>
    47                 <value>classpath*:/domain/*.hbm.xml</value>
    48             </list>
    49         </property>
    50         <!-- 扫描实体类包 -->
    51         <property name="packagesToScan">
    52             <value>domain</value>
    53         </property>
    54         <!-- 实体类 -->
    55         <property name="annotatedClasses">
    56             <list>
    57                 <value>domain.UserEntity</value>
    58             </list>
    59         </property>
    60     </bean>
    61 
    62     <!-- 创建声明式事务管理 -->
    63     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    64         <property name="sessionFactory" ref="sessionFactory"/>
    65     </bean>
    66     <!-- 事务通知(注解方式) -->
    67     <tx:annotation-driven transaction-manager="transactionManager"/>
    68 
    69     <!-- 事务通知(aop方式) -->
    70     <!--<tx:advice id="txAdvice" transaction-manager="transactionManager">
    71         <tx:attributes>
    72             &lt;!&ndash; propagation配置传播行为,isolation配置隔离方式 &ndash;&gt;
    73             <tx:method name="*" propagation="REQUIRED" isolation="READ_COMMITTED" />
    74         </tx:attributes>
    75     </tx:advice>
    76 
    77     &lt;!&ndash; aop织入通知 &ndash;&gt;
    78     <aop:config>
    79         <aop:pointcut id="serviceOption" expression="(execution(* service.serviceImpl.*.*(..)) and (execution(* dao.daoImpl.*.*(..))))"/>
    80         <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOption"/>
    81     </aop:config>-->
    82 
    83 
    84 </beans>
    View Code

      SSHDemo整合配置源码位置:https://gitee.com/codecaijh/SSHDemo

    三、可能遇到的问题

      在整合mybatis的时候可能会遇到 BindingException: Invalid bound statement (not found): dao.daoInterface.UserDao.getUserInfo dao接口类和mapper文件绑定失败而找不到实现方法的异常。

      

       查看target目录下的classes文件时发现没有任何xml文件,推断项目编译的时候可能没把它包含进去。

      解决办法:

      在pom.xml文件中添加如下内容:(表示让maven将以xml和properties等为后缀的文件在构建的时候从资源路径加载到目标路径)

     1 <build>
     2     
     3       <resources>
     4           <resource>
     5               <directory>src/main/java</directory>
     6               <includes>
     7                   <include>**/*.properties</include>
     8                   <include>**/*.xml</include>
     9               </includes>
    10               <filtering>false</filtering>
    11           </resource>
    12       </resources>
    13   </build>

      资源往往不是代码,无需编译,而是一些properties或XML配置文件,构建过程中会往往会将资源文件从源路径复制到指定的目标路径。

     配置说明

    • resources,build过程中涉及的资源文件
      • targetPath,资源文件的目标路径
      • filtering,构建过程中是否对资源进行过滤,默认false
      • directory,资源文件的路径,默认位于${basedir}/src/main/resources/目录下
      • includes,一组文件名的匹配模式,被匹配的资源文件将被构建过程处理
      • excludes,一组文件名的匹配模式,被匹配的资源文件将被构建过程忽略。同时被includes和excludes匹配的资源文件,将被忽略。
    • filters,给出对资源文件进行过滤的属性文件的路径,默认位于${basedir}/src/main/filters/目录下。属性文件中定义若干键值对。在构建过程中,对于资源文件中出现的变量(键),将使用属性文件中该键对应的值替换。
    • testResources,test过程中涉及的资源文件,默认位于${basedir}/src/test/resources/目录下。这里的资源文件不会被构建到目标构件中
  • 相关阅读:
    ManualResetEvent详解
    MEF搜索范围
    ThreadStart和ParameterizedThreadStart区别
    快速理解C#高级概念(一) Delegate委托
    c# 多线程 --Mutex(互斥锁)
    sql server 得到数据库字典
    遇到的坑:在线用户统计的实现
    asp.net core 使用EF7 Code First 创建数据库,同时使用命令创建数据库
    使用cachemanager做缓存(Session的缓存)
    C# web api返回类型设置为json的两种方法
  • 原文地址:https://www.cnblogs.com/caijh/p/7755479.html
Copyright © 2011-2022 走看看