Mybatis与Spring的整合

整合环境搭建

导入 jar包(以下jar包仅供参考,请根据官方文档选择对应版本的jar包)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4. 导入MySQL驱动 jar包

  1. 在这里插入图片描述
    案例:
    db .properties配置:
#mysql
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=CST
jdbc.username=root
jdbc.password=123456
jdbc.maxTotal =123
jdbc.maxIdle =10
jdbc.initialSize =5

#p6spy
#driver=com.p6spy.engine.spy.P6SpyDriver
#url=jdbc:p6spy:mysql://localhost:3306/dt48
#username=root
#password=root

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.no10.po" />
    </typeAliases>

    <!--配置Mapper的位置 -->
    <!-- 关联局部配置文件 -->
    <mappers>
        <mapper resource="com/no10/po/CustomerMapper.xml"/>
        <!-- Mapper接口开发方式 -->
        <mapper resource="com/no10/mapper/CustomerMapper.xml"/>
    </mappers>
</configuration>

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: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/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
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--读取db.properties -->
    <context:property-placeholder location="classpath:com/no10/resource/db.properties"/>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <!--数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}" />
        <!--连接数据库的url -->
        <property name="url" value="${jdbc.url}" />
        <!--连接数据库的用户名 -->
        <property name="username" value="${jdbc.username}" />
        <!--连接数据库的密码 -->
        <property name="password" value="${jdbc.password}" />
        <!--最大连接数 -->
        <property name="maxActive" value="${jdbc.maxTotal}" />
        <!--最大空闲连接  -->
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <!--初始化连接数  -->
        <property name="initialSize" value="${jdbc.initialSize}" />
    </bean>
    <!-- 4.事务管理器,依赖于数据源 -->
    <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 name="configLocation" value="classpath:com/no10/resource/mybatis.xml"/>
    </bean>
    <!--实例化Dao -->
    <bean id="customerDao" class="com.no10.dao.impl.CustomerDaoImpl">
        <!-- 注入SqlSessionFactory对象实例-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>
    <!-- Mapper代理开发(基于MapperFactoryBean) -->
     <bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.no10.mapper.CustomerMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
    </bean>

    <!-- 将dao层类中的方法与xxx.xml中的sql语句关联 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.no10.mapper" />
    </bean>

    <!-- 开启扫描 -->
    <context:component-scan base-package="com.no10.service" />
</beans>

实体类:

public class Customer {
    private int id;
    private String username;
    private String jobs;
    private String phone;

    public int getId() {
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}

传统Dao方式开发整合

采用传统DAO开发方式进行MyBatis与Spring框架的整合时,可以使用mybatis-spring包中所提供的SqlSessionTemplate类或SqlSessionDaoSupport类来实现。
●SqlSessionTemplate: 是mybatis -spring的核心类,它负责管理MyBatis的SqlSession,调用MyBatis的SQL方法。当调用SQL方法时,SqlSessionTemplate将会保证使用的SqlSession和当前Spring的事务是相关的。它还管理SqlSession的生命周期,包含必要的关闭、提交和回滚操作。
●SqlSessionDaoSupport: 是- - 个抽象支持类,它继承了DaoSupport类,主要是作为DAO的基类来使用。可以通过SqlSessionDaoSupport类的getSqlSession0方法来获取所需的SqlSession。

与实体类同包下实现mapper映射文件:

<?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">
<!--
   namespace:命名空间,其值为某一个dao层类的具体路径
 -->
<mapper namespace="com.no10.po.CustomerMapper">
   <!-- sql语句保存在Mybatis的局部配置文件中 -->
   <!--
      select标签存放查询语句(List<User>)
         id:在整个配置文件中id值必须唯一,其值与dao层类中的方法名保持一致
         resultType:指定当前sql查询语句返回的数据类型。类型不是为sql语句的最终类型,而是某一条数据的类型
    -->
   <select id="findCustomerById" resultType="customer" parameterType="Integer">
      SELECT * FROM customer where id = #{id}
   </select>
</mapper>

创建dao接口及实现类:

public interface CustomerDao {
    //通过id查询客户
    public Customer findCustomerById(Integer id);
}
public class CustomerDaoImpl extends SqlSessionDaoSupport implements CustomerDao {
    @Override
    public Customer findCustomerById(Integer id) {
        return this.getSqlSession().selectOne("com.no10.po.CustomerMapper.findCustomerById",id);
    }
}

测试类:

public class DaoTest {
    public static void main(String[] args) {
        findCustomerByIdDaoTest();
    }

    public static void findCustomerByIdDaoTest(){
        ApplicationContext act = new ClassPathXmlApplicationContext("com/no10/resource/applicationContext.xml");
        // 根据容器中Bean的id来获取指定的Bean
        CustomerDao customerDao =(CustomerDao) act.getBean("customerDao");
        //      CustomerDao customerDao = act.getBean(CustomerDao.class);
        Customer customer = customerDao.findCustomerById(1);
        System.out.println(customer);
    }

}

Mapper接口方式开发整合

在MyBatis+Spring的项目中,虽然使用传统的DAO开发方式可以实现所需功能,但是采用这种方式在实现类中会出现大量的重复代码,在方法中也需要指定映射文件中执行语句的id,并且不能保证编写时id的正确性(运行时才能知道)为此,我们可以使用MyBatis提供的另外一种编程方式,即使用Mapper接口编程。

基于MapperFactoryBean的整合

MapperFactoryBean是MyBatis-Spring团队提供的一个用 于根据Mapper接口生成Mapper对象的类,该类在Spring配置文件中使用时可以配置以下参数:

  • mapperInterface:用于指定接口;
  • SqlSessionFactory:用于指定SqlSessionFactory;
  • SqlSessionTemplate:用于指定SqlSessionTemplate。如果与SqlSessionFactory同时设定,则只会启用SqlSessionTemplate。
基于MapperScannerConfigurer的整合

在实际的项目中,DAO层会包含很多接口,如果每一个接口都在Spring配置文件中配置,不但会增加工作量,还会使得Spring配置文件非常臃肿。为此,可以采用自动扫描的形式来配置MyBatis中的映射器——采用MapperScanner。

MapperScannerConfigurer类在Spring配置文件中可以配置以下属性:

  • basePackage:指定映射接口文件所在的包路径,当需要扫描多个包时可以使用分号或逗号作为分隔符。指定包路径后,会扫描该包及其子包中的所有文件。
  • annotationClass:指定了要扫描的注解名称,只有被注解标识的类才会被配置为映射器。
  • sqlSessionFactoryBeanName:指定在Spring中定义的SqlSessionFactory的Bean名称。
  • sqlSessionTemplateBeanName:指定在Spring中定义的SqlSessionTemplate的Bean名称。如果定义此属性,则sqlSessionFactoryBeanName将不起作用。
  • markerInterface:指定创建映射器的接口。

MapperScannerConfigurer的使用非常简单,只需要在Spring的配置文件中编写如下代码:

<!-- Mapper代理开发(基于MapperScannerConfigurer) -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.co10.mapper" />
</bean>

通常情况下,MapperScannerConfigurer在使用时只需通过basePackage属性指定需要扫描的包即可,Spring会自动的通过包中的接口来生成映射器。这使得开发人员可以在编写很少代码的情况下,完成对映射器的配置,从而提高开发效率。

在Mapper包下创建接口及映射文件:

public interface CustomerMapper {
   // 通过id查询客户
   public Customer findCustomerById(Integer id);
   
   // 添加客户
   public void addCustomer(Customer customer);

}
<?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.no10.mapper.CustomerMapper">
   <!--根据id查询客户信息 -->
   <select id="findCustomerById" parameterType="Integer"
           resultType="customer">
      select * from customer where id = #{id}
   </select>
   
   <!--添加客户信息 -->
   <insert id="addCustomer" parameterType="customer">
       insert into customer(username,jobs,phone)
       values(#{username},#{jobs},#{phone})
   </insert>
   
</mapper>

创建service接口及实现类:

public interface CustomerService {
    public void addCustomer(Customer customer);
}
@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
   //注解注入CustomerMapper

   @Autowired
   private CustomerMapper customerMapper;
   //添加客户
   @Override
   public void addCustomer(Customer customer) {
      this.customerMapper.addCustomer(customer);
      //int i=1/0; //模拟添加操作后系统突然出现的异常问题
   }


}

测试类:

/**
 * 测试事务
 */
public class TransactionTest {
   public static void main(String[] args) {
      ApplicationContext act = 
             new ClassPathXmlApplicationContext("com/no10/resource/applicationContext.xml");
      CustomerService customerService = act.getBean(CustomerService.class);
      Customer customer = new Customer();
      customer.setUsername("zhangsan2");
      customer.setJobs("manager");
      customer.setPhone("13233334444");
      customerService.addCustomer(customer);
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值