Spring mybatis整合

方案一:传统的dao方式开发

需要自己开发dao层,编写sql语句

  1. 创建项目,引入依赖
    需要注意的是需要导入mybatis和spring整合的包mybatis-spring
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>xm</groupId>
    <artifactId>sm</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- spring所需的包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>

        <!-- mybatis所需的包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!-- mybatis和spring整合的包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>

        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>

        <!-- 数据库连接池 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>

        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.5.0-RC2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  1. 创建pojo
package com.xm.pojo;

import java.util.Date;

public class User {
    private int id;
    private String username;
    private String sex;
    private Date birthday;
    private String address;
      //get,set等方法省略
}
  1. dao层接口及实现
package com.xm.dao;

import com.xm.pojo.User;

public interface UserDao {
    public User selectUserById(int id);
}

接口实现要继承SqlSessionDaoSupport类,该类是mybatis和spring的整合

package com.xm.dao.impl;

import com.xm.dao.UserDao;
import com.xm.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
    @Override
    public User selectUserById(int id) {
        User user = this.getSqlSession().selectOne("com.xm.dao.UserDao.selectUserById", id);//指定到后面需要写的mapper映射文件的命名空间下
        return user;
    }
}
  1. 数据库配置文件db.propertiers
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/sm
jdbc.username = root
jdbc.password = 123
  1. 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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- mybatis的工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 注入mybatis配置文件 -->
        <property name="configLocation" value="classpath:spring-mybatis.xml"></property>
    </bean>

    <!-- 注入sqlSessionFactory -->
    <bean id="userDao" class="com.xm.dao.impl.UserDaoImpl">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
    </bean>
</beans>
  1. mybatis配置文件
<?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="com.xm.pojo"/>
    </typeAliases>

    <!--定义映射文件-->
    <mappers>
        <mapper resource="UserMapper.xml"></mapper>
    </mappers>

</configuration>
  1. 映射文件
<?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="com.xm.dao.UserDao">
    <!-- 需要创建相应的接口,id的值为接口方法名 -->
    <select id="selectUserById" parameterType="int" resultType="User">
        select * from users where id = #{id}
    </select>
</mapper>
  1. 测试
import com.xm.dao.UserDao;
import com.xm.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserDaoTest {

    @Test
    public void testSelectUserById(){
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-applicationContext.xml");
        //获取userDao
        UserDao userDao = context.getBean(UserDao.class);
        User user = userDao.selectUserById(1);
        System.out.println(user);
    }
}

目录结构

方案二:Mapper动态代理开发(不用自己写Dao实现类)

  1. 创建项目
  2. 创建dao接口
package com.xm.dao;

import com.xm.pojo.User;

public interface UserDao {
   User selectUserById(Integer id);
}
  1. 配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="db.properties"/>

    <!-- 连接池 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- mybatis工厂 -->
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- mybatis核心配置文件的位置 -->
        <property name="configLocation" value="classpath:spring-mybatisConfig.xml"/>
    </bean>

    <!-- Mapper动态代理开发 -->
    <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
          <!-- 此处关联到dao层接口 -->
        <property name="mapperInterface" value="com.xm.dao.UserDao"/>
    </bean>
</beans>
  1. 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="com.xm.dao.UserDao">
    <select id="selectUserById" parameterType="Integer" resultType="User">
        select * from users where id = #{id}
    </select>
</mapper>
  1. mtybatis配置文件
<?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="com.xm.pojo"/>
    </typeAliases>

    <mappers>
        <mapper resource="UserMapper.xml"></mapper>
    </mappers>

</configuration>
  1. 测试类
import com.xm.dao.UserDao;
import com.xm.pojo.User;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class JunitTest {

    @Test
    public void testMapper() throws Exception{
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-applicationContext.xml");
        UserDao userDao = applicationContext.getBean(UserDao.class);
        User user = userDao.selectUserById(1);
        System.out.println(user);

    }
}

方案三:Mapper动态代理扫描包形式开发dao

这种方法是对方案二的简化,只需要修改spring配置文件:将最后的mapper动态代理开发修改如下:这样会自动去寻找basePackage下的包中文件,不用为每一个dao层都配置一次动态代理

<!--    &lt;!&ndash; Mapper动态代理开发 &ndash;&gt;-->
<!--    <bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">-->
<!--        <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>-->
<!--        <property name="mapperInterface" value="com.xm.dao.UserDao"/>-->
<!--    </bean>-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 基本包 -->
        <property name="basePackage" value="com.xm.dao"/>
    </bean>