整合spring和mybatis

96
Bbigbug
2017.11.30 12:17* 字数 504

一 环境搭建

文件结构
1 maven jar包

    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.18</version>
    </dependency>
    <!--c3p0数据包-->
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
    </dependency>

    <!--servlet包-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!--测试包-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

    <!--json包-->
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>

    <!--Spring 包-->
    <!--核心 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <!--DAO层 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <!-- web层 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.8.6</version>
    </dependency>
    <!--Spring test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>4.1.7.RELEASE</version>
    </dependency>

    <!-- DAO-MyBatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.3.0</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.3</version>
    </dependency>

    <!--mybatist 其他包-->
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.2</version>
    </dependency>
    <dependency>
      <groupId>asm</groupId>
      <artifactId>asm</artifactId>
      <version>3.3.1</version>
    </dependency>

    <!--mybatis日志文件-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.7.12</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
2 db.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url =jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
jdbc.username =root
jdbc.password = root
3 log4j.properties
log4j.rootLogger=DEBUG,stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

二 原始dao方法

1 定义接口(User.java)
package edu.eurasia.dao;

import edu.eurasia.entity.UserBean;

public interface UserDao {
    UserBean findUser(int id) throws Exception;
}
2 接口实现(UserImpl.java)
  • 继承SqlSessionDaoSupport,使用getSqlSession获取sqlSession,不用手动注入sqlSessionFactory
package edu.eurasia.dao.impl;

import edu.eurasia.dao.User;
import edu.eurasia.entity.UserBean;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;

public class UserImpl extends SqlSessionDaoSupport implements User {
    public UserBean findUserById(int id) throws Exception {
        SqlSession sqlSession = this.getSqlSession();
        UserBean userBean = sqlSession.selectOne("test.findUserById",id);
        return userBean;
    }
}

3 User.xml文件配置(User.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="findUserById" parameterType="int" resultType="edu.eurasia.entity.UserBean">
        SELECT * FROM user WHERE id=#{user.id}
    </select>
</mapper>
4 配置文件引入mybatis配置文件(mybatis-config.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>
    <mappers>
        <mapper resource="mapper/User.xml"></mapper>
    </mappers>
</configuration>
5 配置spring核心配置文件(applicationContext.xml)
<?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.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/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:db.properties" />
    <!--配置c3p0连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置sqlSqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入mybatis核心配置文件-->
        <property name="configLocation" value="mybatis-config.xml"></property>
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置UserImpl,注入sqlSessionFactory-->
    <bean id="userDao" class="edu.eurasia.dao.impl.UserImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>
</beans>
6 测试(UserText.java)
package edu.eurasia;

import edu.eurasia.dao.User;
import edu.eurasia.entity.UserBean;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserText {
    private ApplicationContext applicationContext;

    @Before
    public void setUp()throws Exception{
      //获取spring核心配置文件
        applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
    @Test
    public void findUserById() throws  Exception{
        //根据id获取注入sqlSessionFactory的方法
        User user = (User) applicationContext.getBean("userDao");
        UserBean userBean = user.findUserById(1);
        System.out.println(userBean);
    }
}
执行结果

三 mapper自动映射方法

1 方法一
(1) 定义mapper sql核心配置文件(UserMapper.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="edu.eurasia.dao.UserMapper">
    <select id="findUserByIdMapper" parameterType="int" resultType="edu.eurasia.entity.UserBean">
        SELECT * FROM user WHERE id=#{user.id}
    </select>

</mapper>
((2) 定义接口(UserMapper.java)
package edu.eurasia.dao;

import edu.eurasia.entity.UserBean;

public interface UserMapper {
    UserBean findUserByIdMapper(int id) throws Exception;
}
((3) 配置文件引入mybatis配置文件(mybatis-config.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>
    <mappers>
        <mapper resource="mapper/User.xml"></mapper>
        <mapper resource="mapper/UserMapper.xml"></mapper>
    </mappers>
</configuration>
((4) spring核心配置文件(applicationContext.xml)
<?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.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/cache
       http://www.springframework.org/schema/cache/spring-cache.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:db.properties" />
    <!--配置c3p0连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置sqlSqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入mybatis核心配置文件-->
        <property name="configLocation" value="mybatis-config.xml"></property>
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置UserImpl,注入sqlSessionFactory-->
    <bean id="userDao" class="edu.eurasia.dao.impl.UserImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
    </bean>

    <!-- mapper配置MapperFactoryBean:根据mapper接口生成代理对象-->
   <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
          <!--注入sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
           <!--给出需要扫描Dao接口包-->
        <property name="mapperInterface" value="edu.eurasia.dao.UserMapper"></property>
    </bean>
</beans>
((5) 测试(MapperText.java)
package edu.eurasia;
import edu.eurasia.dao.UserMapper;
import edu.eurasia.entity.UserBean;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MapperText {
    private ApplicationContext applicationContext;

    @Before
    public void setUp()throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
    @Test
    public void findUserById() throws  Exception{
        UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
        UserBean userBean = userMapper.findUserByIdMapper(1);
        System.out.println(userBean);
    }
}
测试结果
缺点
  • MapperFactoryBean 需要针对每个mapper进行配置
2 方法 二
  • 针对方法一存在问题,做以下改进
(1) 优化applicationContext.xml配置文件
  • mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
  • 遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录 中
  • 自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
  • 如果扫描多个包,每个包中间使用半角逗号分隔
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 指定扫描的包名,如果扫描多个包,每个包中间使用半角逗号分隔 -->
       <property name="basePackage" value="edu.eurasia.dao"></property>
       <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
   </bean>
(2) 测试
package edu.eurasia;
import edu.eurasia.dao.UserMapper;
import edu.eurasia.entity.UserBean;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class MapperText {
    private ApplicationContext applicationContext;

    @Before
    public void setUp()throws Exception{
        applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    }
    @Test
    public void findUserById() throws  Exception{
        UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
        UserBean userBean = userMapper.findUserByIdMapper(3);
        System.out.println(userBean);
    }
}
测试结果

总结

  • spring整合mabatis,使用方法二也就是自动扫描时,理论是不需要在mybatis核心配置文件中引入sql配置文件的,可事实是不引入会报错(不明,待解决)
<?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>
    <mappers>
        <mapper resource="mapper/User.xml"></mapper>
        <!--去掉引入sql文件-->
        <!--<mapper resource="mapper/UserMapper.xml"></mapper>-->
    </mappers>
</configuration>
错误信息

问题解决2018-4-25

阐述

在eclipse中mapper文件和mapper.xml配置文件是在同一目录下,所以上述配置就可以实现mapper的动态代理。
但是,在idea中,所有的配置文件都是在resources资源文件下,就引起mapper文件和mapper.xml配置文件不在同一目录下,所以,就会出现上述错误。

解决

在spring-dao配置文件中,在配置SqlSessionFactory对象时,加入自动扫描mapper.xml的配置文件

    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 注入mybatis核心配置文件:sqlMapConfig.xml -->
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>
MyBatis学习笔记
Web note ad 1