SpringBoot series of tutorials integrated Mybatis

SpringBoot series of tutorials integrated Mybatis

Preparing the environment: IDEA + maven

This blog by way of example, describes two methods Springboot integrated Mybatis, a method is achieved by annotations, one is by way xml

Experiment, first create a Initializer project, as:
Here Insert Picture Description
a packaging jar to choose, because Springboot use embedded Servlet container, jar can be run directly, even if the web project is also supported by
Here Insert Picture Description
select the necessary jar, Mybatis, database it is necessary to drive
Here Insert Picture Description
the new projects will be added automatically follows, that if your mysql server is version 5.7, it is recommended to specify mysql-connector-java version, Druid also need to add their own, pom configuration reference:

<properties>
        <java.version>1.8</java.version>
        <druid.version>1.1.2</druid.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.27</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

mybatis-spring-boot-starter is a starter Springboot scene, as the default integrated jar
Here Insert Picture Description
new databases and data tables:

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `springboot`;

/*Table structure for table `sys_user` */

DROP TABLE IF EXISTS `sys_user`;

CREATE TABLE `sys_user` (
  `userId` int(10) NOT NULL,
  `username` varchar(20) NOT NULL,
  `sex` char(10) DEFAULT NULL,
  `password` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`userId`),
  UNIQUE KEY `idx_username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*Data for the table `sys_user` */

insert  into `sys_user`(`userId`,`username`,`sex`,`password`) values (1,'admin','man','11');

Create a bean class code:


import java.io.Serializable;

public class User implements Serializable{
    private String userId;
    private String username;
    private String sex;
    private String password;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Of course, the configuration database and JDBC connection pool, with specific reference to my blog: SpringBoot series of integrated Druid monitoring configuration data source

  • Annotations way
    for mybatis annotation mode, it is easy to use, create a new Mapper interface can:
import com.example.springboot.mybatis.bean.User;
import org.apache.ibatis.annotations.*;

public interface UserMapper {
    @Select("select * from sys_user where userId=#{userId}")
    public User getUserById(Integer userId);

    @Delete("delete from sys_user where userId=#{userId}")
    public int deleteUserById(Integer userId);

    @Options(useGeneratedKeys = true,keyProperty = "userId")
    @Insert("insert into sys_user(username,sex,password) values(#{username},#{sex},#{password})")
    public int insertUser(User user);

    @Update("update sys_user set username=#{username} where userId=#{userId}")
    public int updateUser(User user);
}

@Mapper annotations, you can not add on each Mapper, so, we'll create a new class Mybatis configuration, whether to support the transaction, whether to support the hump naming and capitalization are automatically converted plus


import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * <pre>
 * Mybatis配置类
 * </pre>
 *
 * @author nicky
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2019年12月15日  修改内容:
 * </pre>
 */
@Configuration
//开启支持事务管理
@EnableTransactionManagement
// Mapper接口扫描,加上这个就不需要每一个Mapper接口都加@Mapper注解
@MapperScan(basePackages = {"com.example.springboot.mybatis.mapper"})
public class MybatisConfig {

    //配置支持驼峰命名和大小写自动转换
    @Bean
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer(){
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

For convenience, do not write the Service class, direct write the Controller class test interface complies with the specification RestFul


import com.example.springboot.mybatis.bean.User;
import com.example.springboot.mybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <pre>
 *  接口测试类
 * </pre>
 *
 * @author nicky
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2019年12月15日  修改内容:
 * </pre>
 */
@RestController
public class UserController {

    @Autowired
    UserMapper userMapper;
    @GetMapping("/user/{userId}")
    public User getUser(@PathVariable("userId") Integer userId){
        return userMapper.getUserById(userId);
    }

    @PostMapping("/user")
    public User insertDept(User user){
        userMapper.insertUser(user);
        return user;
    }
}

There are Post request, we can only use Postman test, the browser can not test Post Interface
Here Insert Picture Description

  • xml configuration

In application.yml add the following configuration, note mybatis configuration does not belong to the spring, so do not use indentation, yaml not familiar with, you can refer to my blog: SpringBoot series of YAML configuration Usage Study Notes

mybatis:
    # 指定全局配置文件位置
    config-location: classpath:mybatis/mybatis-config.xml
    # 指定sql映射文件位置
    mapper-locations: classpath:mybatis/mapper/*.xml

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"/>
    </settings>
</configuration>

mybatis/mapper/UserMapper.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.example.springboot.mybatis.mapper.SysUserMapper">

    <select id="getApiUserById" resultType="com.example.springboot.mybatis.bean.User">
        SELECT * FROM sys_user WHERE userId=#{id}
    </select>

    <insert id="insertApiUser">
        INSERT INTO sys_user(username,sex,password) VALUES(#{username},#{sex},#{password})
    </insert>
</mapper>

SysUserMapper.java interface code:

package com.example.springboot.mybatis.mapper;

import com.example.springboot.mybatis.bean.User;
import org.apache.ibatis.annotations.Param;

//@Mapper
public interface SysUserMapper {

    User getApiUserById(@Param("id") Integer id);

    void insertApiUser(User user);
}

Interface simple test:


import com.example.springboot.mybatis.bean.User;
import com.example.springboot.mybatis.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * <pre>
 *  测试接口,就不写Service类
 * </pre>
 *
 * @author nicky
 * <pre>
 * 修改记录
 *    修改后版本:     修改人:  修改日期: 2019年12月15日  修改内容:
 * </pre>
 */
@RestController
public class UserController {

    @Autowired
    SysUserMapper userDao;


    /**
     * xml方式获取用户信息
     * @param id
     * @return
     */
    @GetMapping("/api/user/{id}")
    public User getUserById(@PathVariable("id") Integer id){
        return userDao.getApiUserById(id);
    }

}

Postman tool to test:
Here Insert Picture Description

Download code examples: GitHub download link

Guess you like

Origin www.cnblogs.com/mzq123/p/12045389.html