Preface: You can use annotations provided with MyBatis3 to gradually replace XML, such as writing SQL directly to perform data queries using @Select annotations, or writing dynamic SQL using advanced @SelectProvider annotations to address complex business requirements.

If you have any questions about learning Java (learning methods, learning efficiency, how to obtain employment), you can come to consult me at any time, this is my Java exchange learning group: 934623944 we communicate a lot of problems, help each other, there are good learning tutorials and development tools in the group. Notes: Nuggets

1. Basic notes

MyBatis provides the following CRUD annotations:

@select @insert @update @delete Add, Delete, change, and check account for the majority of business operations, it is necessary to master the use of these basic annotations, such as the following code to perform data query without XML:

@mapper public interface UserMapper {@select (” Select * from t_user “) List List (); } Those of you who have used Hibernate may wonder why property injection can be done without mapping. Children’s shoes that have used Mybatis in a traditional project may quickly realize this because global hump mapping is enabled in the configuration file, which is also easier and faster to do in SpringBoot.

If the User attribute mobileNum is used and the corresponding database attribute phoneNum is used, the query result will be null:

[{” userId “, “1”, “username” : “admin”, “password” : “admin”, “mobileNum” : null}, {” userId “, “2”, “username” : “Roots”, “password” : “roots”, “mobileNum” : NULL}] To solve the problem of inconsistent object attributes and field humps, we can specify the mapping using the mapping annotation @results.

2. Mapping annotations

Mybatis mainly provides these mapping annotations:

@ResultMap = ResultMap = ResultMap = ResultMap = ResultMap = ResultMap = ResultMap = ResultMap = ResultMap Property indicates the attribute name of the entity object, and column indicates the corresponding database field name.

@Results({ @Result(property = “userId”, column = “USER_ID”), @Result(property = “username”, column = “USERNAME”), @Result(property = “password”, column = “PASSWORD”), @Result(property = “mobileNum”, column = “PHONE_NUM”) }) @Select(“select * from t_user”) List list();

The query results are as follows:

[{” userId “, “1”, “username” : “admin”, “password” : “admin”, “mobileNum” : “15011791234”}, {” userId “, “2”, “username” : }] In order to facilitate the demonstration and avoid the trouble of writing the mapping relationship by hand, here provides a quick method to generate the mapping result set, the details are as follows:

/ * *

  • Public static String getResultsStr(Class Origin) {StringBuilder StringBuilder = new StringBuilder(); public static String getResultsStr(Class Origin) {StringBuilder StringBuilder = new StringBuilder(); stringBuilder.append(“@Results({\n”); for (Field field : origin.getDeclaredFields()) { String property = field.getName(); // Mapping: Object properties (Hump)-> Database field (underscore) String Column = new PropertyNamingStrategy.SnakeCaseStrategy().translate(field.getName()).toUpperCase(); Append (string. format(” @result (property = “%s “, column =” %s “),\n”, property, column)); } stringBuilder.append(“})”); return stringBuilder.toString(); } The current Main method executes as follows: then we copy the printed information from the console to the interface method.

If you have any questions about learning Java (learning methods, learning efficiency, how to obtain employment), you can come to consult me at any time, this is my Java exchange learning group: 934623944 we communicate a lot of problems, help each other, there are good learning tutorials and development tools in the group. Notes: Nuggets

Advanced notes

MyBatis-3 mainly provides the following advanced annotations for CRUD:

@selectProvider, @insertProvider, @updateProvider, @deleteProvider. These advanced annotations are used in dynamic SQL. For example, @selectProvider contains two annotation properties. Type indicates the tool class, and method indicates a method of the tool class, which is used to return specific SQL.

@mapper public interface UserMapper {@selectProvider (type = UserSqlProvider. Class, method = “list222”) List list2(); } Utility class code is as follows:

public class UserSqlProvider { public String list222() { return “select * from t_user ; }

Detailed tutorial

With some understanding of the above annotations, we use project examples to further reinforce their practical use.

Specific steps

To facilitate the demonstration, the first choice is to build a Web environment, and the database is Mysql 5.5+.

Add configuration Here is to add a data source, configure the hump mapping and enable the console printing of SQL logs. In the project’s resource directory, add application.yml configuration as follows:

Spring: a datasource: # connect MySQL url: JDBC: MySQL: / / localhost: 3306 / socks? useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver

Mybatis: Configuration item: enable the underline to hump automatic conversion. Effect: Automatically injects database fields into object properties according to the hump rule. map-underscore-to-camel-case: true

Logging: level: # Print SQL messages com.hehe.mapper: debug 3. Write data layer code

Here we are familiar with the user information as an example, to write the UserMapper interface and the case to use the UserSqlProvider.

3.1 UserMapper

Add UserMapper interface for data query:

package com.hehe.mapper; @Mapper public interface UserMapper { /**

  • Approach 1: Write SQL using annotations. */ @select (” Select * from t_user “) List List ();

/ * *

  • Method 2: */ @selectProvider (type = usersqlProvider.class, method = “listByUsername”) List listByUsername(String username);

/ * *

  • Extension: Either way, you can append the @Results annotation to specify the mapping of the result set.
  • PS: if the match matches the underline to hump, you can omit it directly. */ @Results({ @Result(property = “userId”, column = “USER_ID”), @Result(property = “username”, column = “USERNAME”), @Result(property = “password”, column = “PASSWORD”), @Result(property = “mobileNum”, column = “PHONE_NUM”) }) @Select(“select * from t_user”) List listSample();

/ * *

  • Extension: Either way, if more than one parameter is involved, you must annotate @param, otherwise you can’t get the parameter using an EL expression. */ @Select(“select * from t_user where username like #{username} and password like #{password}”) User get(@Param(“username”) String username, @Param(“password”) String password);

@SelectProvider(type = UserSqlProvider.class, method = “getBadUser”) User getBadUser(@Param(“username”) String username, @Param(“password”) String password);

3.2 UserSqlProvider

Add UserSqlProvider, the utility class used to generate SQL.

package com.hehe.mapper;

/ * *

Purpose: To dynamically generate SQL based on complex business requirements.

Java <– usermapper.xml)/public class UserSqlProvider {/*

Method 1: You can manually write your own SQL in the methods of the utility class. Public String listByUsername(String username) {return “select * from t_user where username =#{username}”; } / *

Method 2: You can also write dynamic SQL according to the official API. / public String getBadUser(@param (” username “) String username, @param (” password “) String password) {return new SQL() {{SELECT(“”); The FROM (” t_user “); if (username ! = null && password ! = null) {WHERE(” username like #{username} and password like #{password} “); } else {WHERE (” 1 = 2 “); } }}.toString(); 3.3 Entity class User Add the entity class User

public class User { private String userId; private String username; private String password; private String mobileNum; //Getters & Setters} 3.4 Adding database records

Open the Navicat query window and simply use the following script.

USE SOCKS; DROP TABLE IF EXISTS t_user; CREATE TABLE t_user ( USER_ID varchar(50) , USERNAME varchar(50) , PASSWORD varchar(50) , PHONE_NUM varchar(15) ) ;

INSERT INTO T_user VALUES (‘ 1 ‘, ‘admin’, ‘admin’, ‘15011791234’); INSERT INTO T_user VALUES (‘ 2 ‘, ‘roots’,’ roots’, ‘18812342017’); 4. Write code for the control layer

package com.hehe.controller;

@RestController @RequestMapping(“/user/*”) public class UserController {

@SuppressWarnings(“all”) @Autowired UserMapper userMapper;

@GetMapping(“list”) public List list() { return userMapper.list(); }

@GetMapping(“list/{username}”) public List listByUsername(@PathVariable(“username”) String username) { return userMapper.listByUsername(username); }

@GetMapping(“get/{username}/{password}”) public User get(@PathVariable(“username”) String username, @PathVariable(“password”) String password) { return userMapper.get(username, password); }

@GetMapping(“get/bad/{username}/{password}”) public User getBadUser(@PathVariable(“username”) String username, @PathVariable(“password”) String password) { return userMapper.getBadUser(username, password); }

If you have any questions about learning Java (learning methods, learning efficiency, how to obtain employment), you can come to consult me at any time, this is my Java exchange learning group: 934623944 we communicate a lot of problems, help each other, there are good learning tutorials and development tools in the group. Notes: Nuggets