Wechat official account: If you have any questions or suggestions, please leave a message on the background. I will try my best to solve your problems.

preface

As the title, today introduces the integration of SpringBoot and Mybatis and the use of Mybatis, before introducing the use of SpringBoot integration of Mybatis annotated version, the last article introduced the theory of Mybatis, Today, this will not introduce MyBatis theory, the jump is interested in reading: SpringBoot combat (13) | integration MyBatis (notes)

The preparatory work

  • SpringBoot 2.1.3
  • IDEA
  • JDK 8

Create a table

CREATE TABLE `student`  (
  `id` int(32) NOT NULL AUTO_INCREMENT,
  `student_id` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'student id'.`name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT 'name'.`age` int(11) NULL DEFAULT NULL COMMENT 'age'.`city` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '所在城市'.`dormitory` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'dormitory'.`major` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT 'professional',
  PRIMARY KEY (`id`) USING BTREE
)ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
Copy the code

Introduction of depend on

<dependencies>
        <! -- JDBC connection driver -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <! -- Web startup class -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <! -- Mybatis dependency -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <! Druid database connection pool -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.14</version>
        </dependency>
        <! Mysql > connect to Mysql
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
            <scope>runtime</scope>
        </dependency>
        <! -- Paging plugin -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
        <! -- test dependency -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <! -- Springboot Maven plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <! Mybatis Generator plugin for automatic code generation
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>
Copy the code

The mybatis Generator is for automatic code generation and pageHelper is for physical paging.

Project configuration

server:
  port: 8080

spring:
    datasource:
        name: test
        url: JDBC: mysql: / / 127.0.0.1:3306 / test
        username: root
        password: 123456
        #druid configuration
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

## This configuration node is an independent node, many students can easily put this configuration under the spring node, resulting in the configuration can not be recognized
mybatis:
  mapper-locations: classpath:mapping/*.xml  Note: It must correspond to the path of the mapper mapping XML file
  type-aliases-package: com.nasus.mybatisxml.model  Note: the path of the corresponding entity class

# pageHelper pagination plugin
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql
Copy the code

Mybatis Generator configuration file

Note that when configuring the configuration file corresponding to the generator plug-in in POM. XML, add this sentence to pom. XML to specify the path of the configuration file corresponding to the generator plug-in. This is already configured in Pom, see Pom Configuration above.

${basedir}/src/main/resources/generator/generatorConfig.xml
Copy the code

GeneratorConfig. XML:

<?xml version="1.0" encoding="UTF-8"? >

      
<generatorConfiguration>
    <! Database driver: Select the database driver package on your local hard drive -->
    <classPathEntry  location="D: \ repository/mysql/mysql - connector - Java \ 5.1.47 \ mysql connector - Java - 5.1.47. Jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">
        <commentGenerator>
            <property name="suppressDate" value="true"/>
            <! -- Whether to remove automatically generated comments true: yes: false: no -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <! -- Database link URL, username, password -->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="JDBC: mysql: / / 127.0.0.1 / test" userId="root" password="123456">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <! The package name and location of the generated model
        <javaModelGenerator targetPackage="com.nasus.mybatisxml.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <! Generate mapping file package name and location -->
        <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <! The package name and location where the DAO was generated
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.nasus.mybatisxml.mapper" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <! TableName is the name of the table in the database or the name of the view.
        <table tableName="student" domainObjectName="Student" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
    </context>
</generatorConfiguration>
Copy the code

The code comments are more detailed than that.

Code generation process

Step 1: Select edit configuration

Step 2: Select add Maven configuration

Step 3: Add the command mybatis-generator:generate -e and click OK

Step 4: Run the configuration to generate the code

Special attention!! The same table must not run multiple times, because mapper mapping file will generate multiple code, resulting in an error, remember. If you want to run multiple times, please delete the mapper mapping file code generated last time and run again.

Step 5: Check the generated results

Problems encountered

Please refer to other people’s written solutions to problems encountered, where I encountered the database time zone error and only generate Insert method problems. All are solved by reading the following article:

Mybatis Generator automatically generates code and possible problems

Generated code

Entity class: student.java

package com.nasus.mybatisxml.model;

public class Student {

    private Long id;

    private Integer age;

    private String city;

    private String dormitory;

    private String major;

    private String name;

    private Long studentId;

   // omit the get and set methods
}
Copy the code

Mapper interface: studentmapper. Java

package com.nasus.mybatisxml.mapper;

import com.nasus.mybatisxml.model.Student;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface StudentMapper {
    int deleteByPrimaryKey(Long id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Long id);

    // I added the method, corresponding to the mapping file to add this method
    List<Student> selectStudents(a);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}
Copy the code

3. Mapping file studentmapper. XML

<?xml version="1.0" encoding="UTF-8" ? >

      
<mapper namespace="com.nasus.mybatisxml.mapper.StudentMapper" >
  <resultMap id="BaseResultMap" type="com.nasus.mybatisxml.model.Student" >
    <id column="id" property="id" jdbcType="BIGINT" />
    <result column="age" property="age" jdbcType="INTEGER" />
    <result column="city" property="city" jdbcType="VARCHAR" />
    <result column="dormitory" property="dormitory" jdbcType="VARCHAR" />
    <result column="major" property="major" jdbcType="VARCHAR" />
    <result column="name" property="name" jdbcType="VARCHAR" />
    <result column="student_id" property="studentId" jdbcType="BIGINT" />
  </resultMap>

  <sql id="Base_Column_List" >
    id, age, city, dormitory, major, name, student_id
  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
    select 
    <include refid="Base_Column_List" />
    from student
    where id = #{id,jdbcType=BIGINT}
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Long" >
    delete from student
    where id = #{id,jdbcType=BIGINT}
  </delete>

  <insert id="insert" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student (id, age, city, 
      dormitory, major, name, 
      student_id)
    values (#{id,jdbcType=BIGINT}, #{age,jdbcType=INTEGER}, #{city,jdbcType=VARCHAR}, 
      #{dormitory,jdbcType=VARCHAR}, #{major,jdbcType=VARCHAR}, #{name,jdbcType=VARCHAR}, 
      #{studentId,jdbcType=BIGINT})
  </insert>

  <insert id="insertSelective" parameterType="com.nasus.mybatisxml.model.Student" >
    insert into student
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id ! = null" >
        id,
      </if>
      <if test="age ! = null" >
        age,
      </if>
      <if test="city ! = null" >
        city,
      </if>
      <if test="dormitory ! = null" >
        dormitory,
      </if>
      <if test="major ! = null" >
        major,
      </if>
      <if test="name ! = null" >
        name,
      </if>
      <if test="studentId ! = null" >
        student_id,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id ! = null" >
        #{id,jdbcType=BIGINT},
      </if>
      <if test="age ! = null" >
        #{age,jdbcType=INTEGER},
      </if>
      <if test="city ! = null" >
        #{city,jdbcType=VARCHAR},
      </if>
      <if test="dormitory ! = null" >
        #{dormitory,jdbcType=VARCHAR},
      </if>
      <if test="major ! = null" >
        #{major,jdbcType=VARCHAR},
      </if>
      <if test="name ! = null" >
        #{name,jdbcType=VARCHAR},
      </if>
      <if test="studentId ! = null" >
        #{studentId,jdbcType=BIGINT},
      </if>
    </trim>
  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    <set >
      <if test="age ! = null" >
        age = #{age,jdbcType=INTEGER},
      </if>
      <if test="city ! = null" >
        city = #{city,jdbcType=VARCHAR},
      </if>
      <if test="dormitory ! = null" >
        dormitory = #{dormitory,jdbcType=VARCHAR},
      </if>
      <if test="major ! = null" >
        major = #{major,jdbcType=VARCHAR},
      </if>
      <if test="name ! = null" >
        name = #{name,jdbcType=VARCHAR},
      </if>
      <if test="studentId ! = null" >
        student_id = #{studentId,jdbcType=BIGINT},
      </if>
    </set>
    where id = #{id,jdbcType=BIGINT}
  </update>

  <update id="updateByPrimaryKey" parameterType="com.nasus.mybatisxml.model.Student" >
    update student
    set age = #{age,jdbcType=INTEGER},
      city = #{city,jdbcType=VARCHAR},
      dormitory = #{dormitory,jdbcType=VARCHAR},
      major = #{major,jdbcType=VARCHAR},
      name = #{name,jdbcType=VARCHAR},
      student_id = #{studentId,jdbcType=BIGINT}
    where id = #{id,jdbcType=BIGINT}
  </update>

  <! -- the method I added -->
  <select id="selectStudents" resultMap="BaseResultMap">
    SELECT
    <include refid="Base_Column_List" />
    from student
  </select>
</mapper>
Copy the code

Serviec layer

1. Interface:

public interface StudentService {

    int addStudent(Student student);

    Student findStudentById(Long id);

    PageInfo<Student> findAllStudent(int pageNum, int pageSize);

}
Copy the code

2. Implementation classes

@Service
public class StudentServiceImpl implements StudentService{

    // Error will be reported, no impact
    @Resource
    private StudentMapper studentMapper;

    /** * Add student information *@param student
     * @return* /
    @Override
    public int addStudent(Student student) {
        return studentMapper.insert(student);
    }

    /** * Query student information based on id *@param id
     * @return* /
    @Override
    public Student findStudentById(Long id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    /** * query all student information *@param pageNum
     * @param pageSize
     * @return* /
    @Override
    public PageInfo<Student> findAllStudent(int pageNum, int pageSize) {
        // Pass parameters to this method to implement physical paging, very simple.
        PageHelper.startPage(pageNum, pageSize);
        List<Student> studentList = studentMapper.selectStudents();
        PageInfo result = new PageInfo(studentList);
        returnresult; }}Copy the code

The controller layer

@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/{id}")
    public Student findStidentById(@PathVariable("id") Long id){
        return studentService.findStudentById(id);
    }

    @PostMapping("/add")
    public int insertStudent(@RequestBody Student student){
        return studentService.addStudent(student);
    }

    @GetMapping("/list")
    public PageInfo<Student> findStudentList(@RequestParam(name = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10") int pageSize){
        returnstudentService.findAllStudent(pageNum,pageSize); }}Copy the code

Start the class

@SpringBootApplication
@MapperScan("com.nasus.mybatisxml.mapper") // Scan mapper interface, must be added
public class MybatisxmlApplication {

    public static void main(String[] args) { SpringApplication.run(MybatisxmlApplication.class, args); }}Copy the code

A mouth, @ MapperScan (” com. Nasus. Mybatisxml. Mappe “) this annotation is the key, the corresponding project mapper (dao) of the package path, must add, otherwise it will cause an exception.

Postman test

1. Insertion method:

2, query method by id:

3, paging query method:

Download the source code

https://github.com/turoDog/Demo/tree/master/springboot_mybatisxml_demo

Can you point a star for me?

After the language

If this article is of any help to you, please help to read it. Your good looks are my motivation to keep writing.

In addition, after paying attention to send 1024 can receive free learning materials. Python, C++, Java, Linux, Go, front-end, algorithm sharing