spring与mybatis的整合

2018-06-29 06:16:49来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

整合的思路

 

SqlSessionFactory对象放到spring容器中作为单例存在。

传统dao的开发方式中,从spring容器中获得sqlsession对象。

Mapper代理形式中,从spring容器中直接获得mapper的代理对象。

数据库的连接以及数据库连接池事务管理都交给spring容器来完成。

 

整合需要的jar包

要实现spring与mybatis的整合,就要首先导入相关的依赖jar包,如下:

    •   Spring的jar包
    •   Mybatis的jar包
    •   Spring与mybatis整合的jar包
    •   Mysql数据库驱动的jar包
    •   Druid数据库连接池的jar包
    •   Spring与Junit集成测试的jar包(spring-test、Junit)
    •   日志的jar包

 

  具体依赖

<properties>
      <spring-version>4.2.4.RELEASE</spring-version>
  </properties>
  
  <dependencies>
      <!-- spring 核心 -->
      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-expression</artifactId>
        <version>${spring-version}</version>
    </dependency>
    
    <!-- spring web集成 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring-version}</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
    <!-- spring aop的jar包 -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>${spring-version}</version>
    </dependency>
    
    <dependency>
        <groupId>aopalliance</groupId>
        <artifactId>aopalliance</artifactId>
        <version>1.0</version>
    </dependency>
      
      <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.8</version>
    </dependency>
      
     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>${spring-version}</version>
    </dependency>
      
      <!-- spring jdbc jar包 -->
          <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring-version}</version>
    </dependency>
      
      <!-- mysql驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.38</version>
    </dependency>
    <!-- 事务 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring-version}</version>
    </dependency>
    
    <!-- druid数据库连接池 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.18</version>
    </dependency>
      
      <!-- mybaties的依赖包 -->
      <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.2.7</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.2.2</version>
    </dependency>
    <!-- 日志相关的jar包 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.13</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
  
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    
    <!-- spring与Junit测试的jar包 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring-version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.9</version>
        <scope>test</scope>
    </dependency>
          
  </dependencies>
  
  <build>  
    <plugins>  
        <plugin>  
            <groupId>org.apache.maven.plugins</groupId>  
            <artifactId>maven-compiler-plugin</artifactId>  
            <configuration>  
                <source>1.7</source>
                <target>1.7</target>  
            </configuration>  
        </plugin>  
        <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <!-- 指定端口 -->
                    <port>8080</port>
                    <!-- 请求路径 -->
                    <path>/</path>
                </configuration>
            </plugin>
        
    </plugins>  
</build>

 

整合的步骤

 

  第一步:创建maven的web工程

  第二步:导入整合需要的jar包

  第三步:mybatis的核心配置文件:sqlMapConfig.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
 <configuration>
     <!-- 定义别名 -->
     <typeAliases>
         <package name="cn.itcast.spring.domain"/>
     </typeAliases>
     <!-- 加载映射文件 -->    
     <mappers>
         <mapper resource="mapper.xml"/>
     </mappers>
 </configuration>    

 

  第四步:spring的核心配置文件:applicationContext.xml的配置

    •     加载db.properties属性配置文件
    •     配置Druid数据库连接池
    •     将SqlSessionFactory的单例对象,配置到spring容器中
    •     将mapper代理对象或者dao接口的实现类对象,配置到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:context="http://www.springframework.org/schema/context"
    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.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">            
    <context:component-scan base-package="cn.spring"></context:component-scan>
    
    <!-- 加载db.properties属性文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    
    <!-- SQLSessionFactory的配置 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>        
        <!-- mybatis的核心配置文件的路径 -->
        <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
    </bean>       
</beans>

 

      至于将mapper代理对象或者dao接口的实现类对象,配置到spring容器中,将在下面进行配置

 

  第五步:编写dao接口、dao实现类或者mapper接口、mapper映射文件

 传统Dao开发方式

  开发方式:dao接口+dao实现类。

  Dao的实现类需要从spring容器中获取sqlSession对象来操作数据库,spring为我们提供了SqlsessionDaoSupport类,我们只需要继承这个类,就可以顺利的获得sqlSession对象。

总结一句话:dao实现类需要继承SqlsessionDaoSupport类,然后再spring容器中配置这个bean。

1 public interface AccountDao {
2     public List<Account> findAll();
3 }
 1 public class AccountDaoImpl extends SqlSessionDaoSupport implements AccountDao {//需要继承SqlSessionDaoSupport 
 2     @Override
 3     public List<Account> findAll() {
 4         SqlSession sqlSession = getSqlSession();    //继承SqlSessionDaoSupport 后直接调用getSqlSession方法
 5         List<Account> selectList = sqlSession.selectList("test.abc");
 6         //整合后sqlSession不需要关闭
 7         return selectList;
 8     }
 9 
10 }

      mapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="test">
    <select id="abc" resultType="account">
        select * from account
    </select>
</mapper>

      applicationContext.xml中配置dao

   <!-- dao的实现类放到容器中(spring与mybatis整合传统dao的开发) -->
    <bean id="accountDao" class="cn.itcast.spring.dao.AccountDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

 

      基于mapper代理形式开发Dao

          开发mapper接口及mapper映射文件

1 public interface AccountMapper {
2     public List<Account> selectAll();
3 }
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
  mapper代理的开发规则:
    1.namespace必须为接口的全路径
    2.id必须和接口的方法名称一致
    3.parameterType必须与接口方法的参数类型一致
    4.resultType必须与接口方法的返回值类型一致
-->
<mapper namespace="cn.itcast.spring.mapper.AccountMapper"> <select id="selectAll" resultType="account"> select * from account </select> </mapper>

 

          applicationContext.xml中配置mapper代理

   <!-- 包扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描包,mapper接口和映射对象的名称必须保持一致 -->
        <property name="basePackage" value="cn.spring.mapper"></property>
    </bean>

 

 

 

  第六步:编写Junit测试代码测试

      传统dao方式开发测试

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @ContextConfiguration("classpath:applicationContext.xml")
 3 public class SpringMybatisTest {
 4     @Autowired
 5     private AccountDao accountDao;
 6     
 7     @Test
 8     public void testName() throws Exception {
 9         List<Account> findAll = accountDao.findAll();        
10         for (Account account : findAll) {
11             System.out.println(account);
12         }
13     }
14 }

 

 

      基于mapper代理方式测试

 1 @RunWith(SpringJUnit4ClassRunner.class)
 2 @ContextConfiguration("classpath:applicationContext.xml")
 3 public class SpringMybatisTest {
 4     @Autowired
 5     private AccountMapper accountMapper;
 6     
 7     @Test
 8     public void testName() throws Exception {
 9         List<Account> list = accountMapper.selectAll();        
10         for (Account account : list) {
11             System.out.println(account);
12         }
13     }
14 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:PACKAGE-INFO.JAVA 作用及用法详解

下一篇:Maven安装配置环境变量及eclipse的配置