SpringBoot2.x learning - integrated Mybatis framework

Posted by AngelG107 on Sat, 08 Feb 2020 13:55:09 +0100

1, Add startup dependency

Add dependency in maven file of spring boot project as follows:

 <properties>
        <java.version>1.8</java.version>
        <druid.version>1.1.13</druid.version>
        <mybatis.version>2.1.0</mybatis.version>
        <druid.version>1.1.21</druid.version>
    </properties>

 <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
 </dependency>

The initiator depends on the following

Two, configuration

1. Configure @ MapperScan annotation in the startup class * Application to tell Spring Boot which packages to scan for Mapper interface. as follows

@SpringBootApplication
@MapperScan(basePackages = "com.soft.fireadmin.platform.*.dao")
public class FireAdminApplication {

    public static void main(String[] args) {
        SpringApplication.run(FireAdminApplication.class, args);
    }

}

The annotation @ MapperScan provided by mybatis spring will automatically scan the Java interface under the specified package and assemble these classes into the Spring IoC container.

Or mark @ Mapper annotation on each Mapper interface, so that SpringBoot will automatically scan the Java interface under the package, and Spring will automatically create the implementation class corresponding to Mapper interface and register it as Spring Bean.

(2) Simple configuration of application.properties is as follows

#If the XML corresponding to the interface method is placed in the resources directory, you need to tell Mybatis where to scan Mapper
mybatis.mapper-locations=classpath:mapper/**/*.xml
#Packages that define Alias scans need to be used with @ Alias
mybatis.type-aliases-package=com.soft.admin
#Specify that the complex configuration of Mybatis configuration file can be written in a single xml
mybatis.config-location=classpath:mybatis/mybatis-config.xml
#Configure the Mybatis plug-in and interceptor
mybatis.configuration.interceptors=.....
#Cascade load property configurationwhen on, any method call loads all properties of the object. Otherwise, each property is loaded on demand
#Before 3.4.1, the default value is true
mybatis.configuration.aggressive-lazy-loading=false
#Configure the default actuator. SIMPLE is a common executor; REUSE executors REUSE prepared statements;
# The BATCH executor will reuse statements and perform BATCH updates.
mybatis.executor-type=simple

3, Write code

(1) Write the controller class EmpController.java under the controller package

/**
 * Employee controller
 *
 * @author David Lin
 * @version: 1.0
 * @date 2019-11-10 22:35
 */
@RestController
@RequestMapping("/emp")
public class EmpController {

    @Resource
    private EmpService empService;

    @RequestMapping("/findall")
    public List<Emp> findAllEmpList(HttpServletRequest request) {
          return empService.findAllEmpList();
    }

 
}

(2) Write the business logic processing classes EmpService.java and EmpServiceImpl.java under the service package

/**
 * Employee business interface
 *
 * @author David Lin
 * @version: 1.0
 * @date 2019-11-10 22:33
 */
public interface EmpService {
    /**
     * Query all employees list
     * @return
     */
    List<Emp> findAllEmpList();

    /**
     * Get employee information according to employee number
     * @param empno
     * @return
     */
    Emp getEmpById(String empno);
}
------------------------------
/**
 * Implementation of employee business interface
 *
 * @author David Lin
 * @version: 1.0
 * @date 2019-11-10 22:32
 */
@Service("empService")
public class EmpServiceImpl implements EmpService {
    /**
     * Employee data operation object
     */
    @Resource
    private EmpMapper empMapper;

    @Override
    public List<Emp> findAllEmpList() {
        return empMapper.findAllEmpList();
    }

    @Override
    public Emp getEmpById(String empno) {
        return empMapper.getEmpById(empno);
    }
}

(3) Write data provider and Mapper XML Mapping Files EmpMapper.java and EmpMapper.xml under dao package

/**
 * Employee data operation interface
 *
 * @author David Lin
 * @version: 1.0
 * @date 2019-11-10 22:12
 */
public interface EmpMapper {
    /**
     * Query all employees list
     * @return
     */
     List<Emp> findAllEmpList();

    /**
     * Get employee information according to employee number
     * @param empno
     * @return
     */
     Emp getEmpById(String empno);
}
<?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.soft.fireadmin.platform.emp.dao.EmpMapper">

    <resultMap id="BaseResultMap" type="com.soft.fireadmin.platform.emp.model.Emp">
        <id column="empno" property="empno" jdbcType="DOUBLE"/>
        <result column="ename" property="ename" jdbcType="VARCHAR"/>
        <result column="job" property="job" jdbcType="VARCHAR"/>

        <result column="mgr" property="mgr" jdbcType="DOUBLE"/>
        <result column="hiredate" property="hiredate" jdbcType="DATE"/>
        <result column="sal" property="sal" jdbcType="DOUBLE"/>
        <result column="comm" property="comm" jdbcType="DOUBLE"/>
        <result column="deptno" property="deptno" jdbcType="DOUBLE"/>

    </resultMap>

     <select id="findAllEmpList" resultMap="BaseResultMap">
            select  e.*  from emp e
     </select>

    <select id="getEmpById" resultMap="BaseResultMap">
         select  e.*  from emp e where e.empno=#{empno,jdbcType=VARCHAR}
    </select>

</mapper>

(4) Write the persistence class Emp.java under the model package

/**
 * Employee entity object
 *
 * @author David Lin
 * @version: 1.0
 * @date 2019-03-17 11:30
 */
@Setter
@Getter
@ToString
public class Emp {
    /**
     * Employee number
     */
    private int empno;
    /**
     * Employee name
     */
    private String  ename;
    /**
     * Post
     */
    private String job;
    /**
     * Leader number
     */
    private int mgr ;
    /**
     * Entry time
     * Custom output format
     */
    @JsonFormat(locale="zh", timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
    private Timestamp hiredate;
    /**
     * salary
     */
    private double sal;
    /**
     * bonus
     */
    private double comm;
    /**
     * Department No
     */
    private int deptno;
}

4, Attention points

(1)Mapper XML Mapping file will be automatically scanned if it is put together with mapper interface, but Maven project will be omitted when packaging. At this time, the following configuration needs to be added to Maven configuration file pom.xml to avoid that mapper XML Mapping file under java directory will be automatically omitted when packaging.

 <resources>
            <!--Maven java Directory xml Resources are ignored when the project is packaged,So the configuration is as follows to prevent mybatis Of xml file ignored-->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

If the mapper xml Mapping file is placed in the resources directory, you need to configure the scan mapper xml path

(2) If the time type of entity object is java.util.Date, when saving and querying, you can configure JDBC type = timestamp in the insertion, update method and result set of XML if the time type is accurate to minutes and seconds, so that the date will be accurate to minutes and seconds when saving.

 

Published 31 original articles, won praise 15, visited 30000+
Private letter follow

Topics: Mybatis xml Java Spring