Spring boot integrates mybatis and precautions

Keywords: Java Mybatis Spring MySQL xml

Main steps

  1. Add dependency on mybatis
  2. Configure data source information in the configuration file
  3. Write the mapping file of the pojo mapper interface maper
  4. Manually configure package scanning of mybatis

Add @ MapperScan to the main startup class

1: import dependency


2: configure data source information

Configure in application.yml

#DB Configation
    driverClassName: com.mysql.jdbc.Driver
   //Note that if there is a problem of unable to connect to the database tx Add later  ?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
    url: jdbc:mysql://
    username: root
    password: 813100
    database: MySQL
    show-sql: true
    generate-ddl: true

3: write pojo entity class and corresponding mapper interface and mapping file

pojo entity class

package com.offcn.springbootdemo1.pojo;

public class UUser {

    private Integer id;
    private String username;
    private String password;
    private String name;
  //Add here set,get,Construction method and rewriting toString

mapper interface

package com.offcn.springbootdemo1.mapper;

import com.offcn.springbootdemo1.pojo.UUser;

import java.util.List;

public interface UUserMapper {
    List<UUser> selectUUser();

mapper mapping file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

<mapper namespace="com.offcn.springbootdemo1.mapper.UUserMapper">
<select id="selectUUser" resultType="com.offcn.springbootdemo1.pojo.UUser">
    select * from user

Note: if the mapper interface and mapper mapping file are in the same place

Then there will be errors in running


1: create a directory structure in the resources directory that is the same as the mapper interface, and put the mapper mapping file in it

2: if you want to put the mapper interface and mapper mapping file together

Then add the following configuration in pom.xml


4: manually configure mybatis scanning

Add annotation @ MapperScan to startup class

package com.offcn.springbootdemo1;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan(basePackages = "com.offcn.springbootdemo1.mapper")
public class Springbootdemo1Application {

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

5: test in Controller

package com.offcn.springbootdemo1.controller;

//Guide bag

public class UUserController {
    private UUserMapper userMapper;

    public List<UUser> selectUUser(){
        List<UUser> uUsers = userMapper.selectUUser();
        return uUsers;

6: in browser and results

Posted by royalsolo on Tue, 05 Nov 2019 06:58:16 -0800