Spring和MyBatis的整合

目录

一、导入jar包

二、整体结构

三、ApplicationContext的配置

四、druid.properties的配置

五、mybatis-config.xml的配置

六、Employee实体类

七、EmployeeMapper

​八、EmployeeMapper.xml

九、EmployService


一、导入jar包

Spring和MyBatis的整合

二、整体结构

Spring和MyBatis的整合

三、ApplicationContext的配置

<?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"
       xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
    <!-- 自动扫描 -->
    <context:component-scan base-package="com.itheima">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
​
    <!-- 引入数据库的配置文件 -->
    <context:property-placeholder location="conf/druid.properties" />
    <!-- 数据库连接池配置 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${driverClassName}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${username}"></property>
        <property name="password" value="${password}"></property>
    </bean>
​
    <!-- spring事务管理 -->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
​
    <!-- 开启基于注解的事务 -->
    <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
​
    <!--
        整合mybatis
            目的:1、spring管理所有组件。mapper的实现类。
                    service==>Dao   @Autowired:自动注入mapper;
                2、spring用来管理事务,spring声明式事务
    -->
    <!--创建出SqlSessionFactory对象  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--指定数据源 -->
        <property name="dataSource" ref="dataSource"></property>
        <property name="typeAliasesPackage" value="com.itheima.entity"></property>
    </bean>
  
    <!--自动扫描com/itheima/dao下的所有dao接口,并实现这些接口,可直接在程序中使用dao接口,不需要在获取sqlsession -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" >
        <property name="basePackage" value="com/itheima/dao"></property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
  
    <!--配置一个可以进行批量执行的sqlSession  -->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg>
        <constructor-arg name="executorType" value="BATCH"></constructor-arg>
    </bean>
  
    <!-- 扫描所有的mapper接口的实现,让这些mapper能够自动注入;
    base-package:指定mapper接口的包名
     -->
    <mybatis-spring:scan base-package="com.itheima.dao"/>
</beans>

四、druid.properties的配置

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000
minIdle=3

五、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>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <setting name="jdbcTypeForNull" value="NULL"/>
        
        <!--显式的指定每个我们需要更改的配置的值,即使他是默认的。防止版本更新带来的问题  -->
        <setting name="cacheEnabled" value="true"/>
        <setting name="lazyLoadingEnabled" value="true"/>
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    
    <databaseIdProvider type="DB_VENDOR">
        <property name="MySQL" value="mysql"/>
        <property name="Oracle" value="oracle"/>
        <property name="SQL Server" value="sqlserver"/>
    </databaseIdProvider>
    
</configuration>

六、Employee实体类

package com.itheima.entity;
​
import java.io.Serializable;
​
public class Employee implements Serializable {
​
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String name;
    private String gender;
    private String email;
    private String did;
​
    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", email='" + email + '\'' +
                ", did='" + did + '\'' +
                '}';
    }
​
    public Employee() {
    }
​
    public Employee(Integer id, String name, String gender, String email, String did) {
        this.id = id;
        this.name = name;
        this.gender = gender;
        this.email = email;
        this.did = did;
    }
​
    public static long getSerialVersionUID() {
        return serialVersionUID;
    }
​
    public Integer getId() {
        return id;
    }
​
    public void setId(Integer id) {
        this.id = id;
    }
​
    public String getName() {
        return name;
    }
​
    public void setName(String name) {
        this.name = name;
    }
​
    public String getGender() {
        return gender;
    }
​
    public void setGender(String gender) {
        this.gender = gender;
    }
​
    public String getEmail() {
        return email;
    }
​
    public void setEmail(String email) {
        this.email = email;
    }
​
    public String getDid() {
        return did;
    }
​
    public void setDid(String did) {
        this.did = did;
    }
}
​

七、EmployeeMapper

package com.itheima.dao;
​
import com.itheima.entity.Employee;
import org.springframework.stereotype.Repository;
​
import java.util.List;
​
@Repository
public interface EmployeeMapper {
​
    public Employee getEmpById(Integer id);
​
    public List<Employee> getEmps();
​
}

​八、EmployeeMapper.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.itheima.dao.EmployeeMapper">
​
    <resultMap id="myEmpById" type="com.itheima.entity.Employee">
        <id property="id" column="id"></id>
        <result property="name" column="id"></result>
        <result property="gender" column="gender"></result>
        <result property="email" column="email"></result>
        <result property="did" column="did"></result>
    </resultMap>
    <!-- public Employee getEmpById(Integer id); -->
    <select id="getEmpById" resultMap="myEmpById">
        SELECT * FROM tb1_employee WHERE id=#{id}
    </select>
    
    <!--public List<Employee> getEmps();  -->
    <select id="getEmps" resultType="com.itheima.entity.Employee">
        SELECT * FROM tb1_employee
    </select>
</mapper>

九、EmployService

package com.itheima.service;
​
import com.itheima.dao.EmployeeMapper;
import com.itheima.entity.Employee;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
​
import java.util.List;
​
@Service
public class EmployeeService {
​
    @Autowired
    private EmployeeMapper employeeMapper;
​
    public Employee getEmp(int id) {
        return employeeMapper.getEmpById(id);
    }
​
    public List<Employee> getEmps(){
        return employeeMapper.getEmps();
    }
​
    @Test
    public void test01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("conf/ApplicationContext.xml");
        EmployeeService employeeService=(EmployeeService)context.getBean("employeeService");
​
        Employee emp = employeeService.getEmp(3);
        System.out.println(emp);
        System.out.println("---------------");
        List<Employee> emps = employeeService.getEmps();
        for(Employee employee:emps){
            System.out.println(employee);
        }
    }
}