MyBatis is an excellent persistence layer framework, which is used by major Internet companies. This paper uses Spring Boot to integrate MyBatis and complete CRUD operation.

Why use Mybatis? Do we need to master Mybatis?

To make it official:

MyBatis is an excellent persistence layer framework that supports customized SQL, stored procedures, and advanced mapping. MyBatis avoids almost all of the JDBC code and manual setting of parameters and fetching result sets. MyBatis can configure and map native information using simple XML or annotations to map interfaces and Java’s POJOs(Plain Ordinary Java Objects) to records in the database.

Utilitarian point:

It is said that at present the major Internet companies usually use Mybatis, but not quickly learn it?

How to use it?

That is the focus of this article.

New Spring Boot project and import Eclipse these here is not worded, will not be able to view just two steps! Eclipse+Maven quickly builds the first Spring Boot project.

1. Add a dependency to pom.xml

Mybatis -spring-boot-starter; I am using MySQL database and need to introduce YSQL-connector-Java.

<! --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <! <dependency> <groupId>org.mybatis. Spring. Boot </groupId> < artifactId > mybatis - spring - the boot - starter < / artifactId > < version > 1.1.1 < / version > < / dependency >Copy the code

2. Application. property Configures Mybatis and data source

mybatis.config-location=classpath:mapper/mybatis_config.xml mybatis.mapper-locations=classpath:mapper/*Mapper.xml mybatis.type-aliases-package=com.shangguan.mybatis.entity spring.datasource.driverClassName = com.mysql.cj.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/spring_boot? serverTimezone=GMT%2B8 spring.datasource.username = root spring.datasource.password = 123456Copy the code

For example my mybatis_config. XML path for mybatis/SRC/main/resources/mapper/mybatis_config XML (below is a directory structure), So my mybatis. Config-location is classpath:mapper/mybatis_config.xml. Please note that mybatis must be configured according to the directory structure of your project. The same goes for databases.

The mapper package contains the Mybatis mapping class.

The interceptor package is an interceptor. If in doubt, please refer to the previous post on Spring Boot configuring interceptors and Implementing cross-domain access

3. Mybatis global configuration file

The MyBatis configuration file contains Settings and properties information that will greatly affect MyBatis behavior. For details about configuration files, see XML mapping configuration files.

mybatis_config.xml

<! DOCTYPE configuration PUBLIC"- / / mybatis.org//DTD Config / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>
Copy the code

4. Entity class User

The User is used the same as before, without modification.

User:

public class User implements Serializable {

    private static final long serialVersionUID = 1L;
    private Long id;
    private String userName;
    private String passWord;

    public User() {
        super();
    }

    public User(String userName, String passWord) {
        super();
        this.userName = userName;
        this.passWord = passWord;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassWord() {
        return passWord;
    }

    public void setPassWord(String passWord) {
        this.passWord = passWord;
    }

    @Override
    public String toString() {
        return "userName " + this.userName + ", pasword "+ this.passWord; }}Copy the code

5. Add the mapping file and mapping class of User

SQL mapping files have a few top-level elements (in the order they should be defined) :

  • Cache – Cache configuration for a given namespace.

  • Cache-ref – References to other namespace cache configurations.

  • ResultMap – The most complex and powerful element describing how to load objects from a database result set.

  • ParameterMap – Obsolete! Old-fashioned style parameter mapping. Inline arguments are preferred. This element may be removed in the future and will not be recorded here.

  • SQL – reusable block of statements that can be referenced by other statements.

  • Insert – Mapping insert statements

  • Update – Mapping update statement

  • Delete – Mapping delete statement

  • Select – Mapping query statement

Refer to the XML mapping file for more information.

Add, delete, modify and query SQL statements are written in usermapper. XML.

There are a few caveats:

Public List getAll(); usermapper.java public List getAll(); When SQL statement has multiple parameters, you need to add @param annotation in the mapping class method, otherwise it will throw an exception saying that the parameter can not be found. Such as: public void updateUser(@Param(“id”) Long id, @Param(“userName”) String userName, @Param(“passWord”) String passWord); UseGeneratedKeys =”true” keyProperty=”id” usermapper. XML: <? The 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.shangguan.mybatis.mapper.UserMapper”> <resultMap id=”BaseResultMap” type=”com.shangguan.mybatis.mapper.UserMapper” > <id column=”id” property=”id” jdbcType=”BIGINT” /> <result column=”userName” property=”userName” jdbcType=”VARCHAR” /> <result column=”passWord” property=”passWord” jdbcType=”VARCHAR” /> </resultMap> <! <select id=”getAll” resultType=”user”> select * from user. <insert id=”saveUser” useGeneratedKeys=”true” keyProperty=”id”> Insert into user(username,password) values(#{userName},#{passWord}) </insert> <! <delete Id =”deleteUserById”> delete from user where Id =#{Id} </delete> <! <update id=”updateUser”> update user set userName = #{userName},passWord = #{passWord} where id= #{id} </update> </mapper> Usermapper. Java: @mapper public interface UserMapper {public List<User> getAll(); public void saveUser(User user); public void deleteUserById(Long id); public void updateUser(@Param(“id”) Long id, @Param(“userName”) String userName, @Param(“passWord”) String passWord); } 6. UserService has four methods: add, delete, change, and check. Query all users, save users, delete users by ID, and update user information. UserService: public interface UserService {public List<User> getAllUser(); public void saveUser(User user); public void deleteUserById(Long id); public void updateUser(Long id, String userName, String passWord); } UserServiceImpl: @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public List<User> getAllUser() { List<User> list = userMapper.getAll(); return list; } @Override public void saveUser(User user) { userMapper.saveUser(user); } @Override public void deleteUserById(Long id) { userMapper.deleteUserById(id); } @Override public void updateUser(Long id, String userName, String passWord) { userMapper.updateUser(id, userName, passWord); }} 7. The Controller layer implements the interface encapsulation in UserController: @RestController @SpringBootApplication @RequestMapping(“/mybatis”) public class UserController { @Autowired private UserService userService; @RequestMapping(“/getAllUser”) public List<User> getAllUser() { List<User> list = userService.getAllUser(); return list; } @RequestMapping(“/saveUser”) public void saveUser(User user) { userService.saveUser(user); } @RequestMapping(“/deleteUserById”) public void deleteUserById(Long id) { userService.deleteUserById(id); } @RequestMapping(“/updateUser”) public void updateUser(Long id, String userName, String passWord) { userService.updateUser(id, userName, passWord); }} to 8. The test start Spring Boot program, use the Postman test: (1) http://localhost:8080/mybatis/getAllUser database access to all the users information and correct: (2) http://localhost:8080/mybatis/saveUser? UserName = aha & passWord = 123321 to add a name to aha, passWord is 123321 users to add success: (3) http://localhost:8080/mybatis/deleteUserById? Id = 6 delete id for users delete successful: (4) http://localhost:8080/mybatis/updateUser? Select * from user where id=7&userName= 3 &passWord=three To sum up, many things always seem easy and difficult to do. Looking at the Online Spring Boot integration tutorial, I feel that it is too easy. In the process of hands-on practice, I will still find some details that need to be paid attention to. Spring Boot (6) : How to gracefully use Mybatis