2021-04-20

MyBatis与Spring的整合

一、准备所需的JAR包
  1. Spring框架所需的JAR包
    在这里插入图片描述

  2. MyBatis框架所需的包

    mybatis的核心包以及其解压文件夹lib中的所有jar包:
    在这里插入图片描述在这里插入图片描述

  3. MyBatis与Spring整合的中间 jar
    在这里插入图片描述

  4. 数据库驱动jar包
    在这里插入图片描述

  5. 数据源所需的jar包

二:编写配置文件
  1. 创建db.properties文件用于连接数据库
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis2
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal=30       //数据库连接池的最大连接数
jdbc.maxIdle=10        //最大空闲数
jdbc.initialSize=5     //初始化连接数
  1. 创建spring的配置文件 (applicationContext.xml)

    步骤:

    1. 定义读取db.properties文件的配置
    2. 配置数据源
    3. 配置事务管理器并开启事务注解
    4. 配置mybatis工厂来与spring整合,其中mybatis工厂用于构建SqlSessionFactory

    需提供两个参数:分别是数据源和mybatis的配置文件路径

<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--读取db.properties-->
    <context:property-placeholder location="classpath:db.properties"/>

    <!--配置数据源-->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxTotal" value="${jdbc.maxTotal}"/>
        <property name="maxIdle" value="${jdbc.maxIdle}"/>
        <property name="initialSize" value="${jdbc.initialSize}"/>
    </bean>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
       <!--注入数据源-->
      <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置MyBatis工厂-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>

        <!--指定核心配置文件位置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!--实例化Dao-->
    <bean id="customerDao" class="com.mybatis.dao.impl.CustomerDaoImpl">
        <!--注入sqlSessionFactory对象实例-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </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.mybatis.po"/>
    </typeAliases>

    <!--配置Mapper的位置-->
    <mappers>
            <!--<mapper resource="CustomerMapper.xml"/>-->
        <mapper resource="com/mybatis/po/CustomerMapper.xml"/>
    </mappers>

</configuration>
  1. 创建log4j.properties配置文件,用于查看控制台输出的SQL语句
# 全局日志配置
log4j.rootLogger=ERROR, stdout
# MyBatis 日志配置
log4j.logger.com.mybatis.po.CustomerMapper=DEBUG
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

三、整合方式

1.传统的DAO方式的开发整合
  1. 实现持久层
public class Customer {
    private Integer id;
    private String username;
    private String jobs;
    private String phone;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getJobs() {
        return jobs;
    }

    public void setJobs(String jobs) {
        this.jobs = jobs;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", jobs='" + jobs + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}
  1. 创建映射文件CustomerMapper.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.mybatis.po.CustomerMapper">

    <select id="findCustomerById" parameterType="Integer" resultType="com.mybatis.po.Customer">
        select * from t_customer where id = #{id};
    </select>
</mapper>
  1. 实现DAO层(创建接口CustomerDao并实现该接口)
public interface CustomerDao {
  //通过id查询客户
    public Customer findCustomerById(Integer id);
}

CustomerDaoImpl继承了SqlSessionDaoSupport类并实现接口CustomerDao

public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao {

  //通过SqlSessionDaoSupport类的getSqlSession()方法来获取所需的SqlSession
    @Override
    public Customer findCustomerById(Integer id) {
        return this.getSqlSession().selectOne("com.mybatis.po.CustomerMapper.findCustomerById",id);
    }
}
  1. 在spring配置文件中编写实例化CustomerDaoImpl的配置
<!--实例化Dao-->
<bean id="customerDao" class="com.mybatis.dao.impl.CustomerDaoImpl">
  <!--注入sqlSessionFactory对象实例-->
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
  1. 整合测试
public class DaoTest {

    @Test
    public void findCustomerByIdTest(){
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        //根据bean容器的id来获取指定的Bean
        CustomerDao customerDao= (CustomerDao) context.getBean("customerDao");
      //执行customerDao实例的方法来查询id
        Customer customer = (Customer) customerDao.findCustomerById(1);
        System.out.println(customer);
    }
}
2.Mapper接口方式的开发整合
1. 基于MapperFactoryBean的整合
  1. 创建CustomerMapper接口以及对应的映射文件
public interface CustomerMapper {
    public Customer findCustomerById(Integer id);
}
<?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.mybatis.mapper.CustomerMapper">
  
    <select id="findCustomerById" parameterType="Integer" resultType="com.mybatis.po.Customer">
        select * from t_customer where id = #{id};
    </select>

</mapper>
  1. 在mybatis核心配置文件中引入映射文件
  2. 在spring的配置文件中创建id为customerMapper的Bean
<!--Mapper代理开发(基于MapperFactoryBean)--> 
<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
         <!--用于指定接口-->
        <property name="mapperInterface" value="com.mybatis.mapper.CustomerMapper"/>
         <!--用于指定sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  1. 执行测试方法
public void findCustomerByIdMapperTest(){
    ClassPathXmlApplicationContext context =
            new ClassPathXmlApplicationContext("applicationContext.xml");

    //根据bean容器的id来获取指定的Bean
    CustomerMapper customerMapper = (CustomerMapper) context.getBean("customerMapper");
    Customer customer = customerMapper.findCustomerById(1);
    System.out.println(customer);
}
2. 基于MapperScannerConfigurer的整合

采用MapperScannerConfigurer类来以自动扫描的形式配置MyBatis中的映射器

  • basePackage: 指定映射接口文件所在的包路径,当有多个包需要扫描的时候可以使用分号或逗号作为分隔符
  • annotationClass: 指定了要扫描的注解名称,只有被注解的类才会配置为映射器
<!-- 基于MapperScannerConfigurer的整合
     Spring会自动地通过包中的接口生成映射器
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.mybatis.mapper"/>
</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值