SpringBoot quickly integrates MyBatis

Artificial intelligence, zero-based entry! http://www.captainbed.net/inner 

Introduction: Using the annotations provided by MyBatis3 can gradually replace XML. For example, using @Select annotations to directly write SQL to complete data query, using @SelectProvider advanced annotations can also write dynamic SQL to meet complex business requirements.

1. Basic notes

MyBatis mainly provides the following CRUD annotations:

@Select

@Insert

@Update

@Delete

Additions, deletions, and changes take up most of the business operations. It is still necessary to master the use of these basic annotations. For example, the following code can complete data query without XML:

@Mapper
public interface UserMapper {
   @Select("select * from t_user")
   List<User> list();
}

Students who have used Hibernate may be curious, why can property injection be completed without configuring the mapping relationship here? Children's shoes that have used Mybatis in traditional projects may react quickly because the global hump mapping is turned on in the configuration file, which can also be done in SpringBoot, and it is simpler and faster.

Although the global camel case mapping is enabled, you may still question that if the field does not comply with the rule of underscore to camel case, the entity object attribute returned by the query will be obtained as null, such as the above User object attribute mobileNum and the corresponding database field phoneNum, then The query result is:

[
 {
   "userId": "1",
   "username": "admin",
   "password": "admin",
   "mobileNum": null
 },
 {
   "userId": "2",
   "username": "roots",
   "password": "roots",
   "mobileNum": null
 }
]

In order to solve the problem of inconsistency between object attributes and field camels, we can use the mapping annotation @Results to specify the mapping relationship.

2. Mapping annotations

Mybatis mainly provides these mapping annotations:

@Results is used to fill in the mapping relationship of multiple fields in the result set.

@Result is used to fill in the mapping relationship of a single field of the result set.

@ResultMap associates <resultMap> in XML according to ID.

For example, in the above list method, we can specify the mapping relationship of the returned result set on the basis of querying SQL, where property represents the attribute name of the entity object, and column represents 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<User> list();

The query results are as follows:

[
 {
   "userId": "1",
   "username": "admin",
   "password": "admin",
   "mobileNum": "15011791234"
 },
 {
   "userId": "2",
   "username": "roots",
   "password": "roots",
   "mobileNum": "18812342017"
 }
]

In order to solve the problem of inconsistency between object attributes and field camels, we can use the mapping annotation @Results to specify the mapping relationship.

In order to facilitate the demonstration and avoid the trouble of manually writing the mapping relationship, here is a method to quickly generate the mapping result set, the specific content is as follows:

/**
    * 1.用于获取结果集的映射关系
    */
   public static String getResultsStr(Class origin) {
       StringBuilder stringBuilder = new StringBuilder();
       stringBuilder.append("@Results({\n");
       for (Field field : origin.getDeclaredFields()) {
           String property = field.getName();
           //映射关系:对象属性(驼峰)->数据库字段(下划线)
           String column = new PropertyNamingStrategy.SnakeCaseStrategy().translate(field.getName()).toUpperCase();
           stringBuilder.append(String.format("@Result(property = \"%s\", column = \"%s\"),\n", property, column));
       }
       stringBuilder.append("})");
       return stringBuilder.toString();
   }

The execution effect of the current Main method is as follows: Then we copy this section of the console print information to the interface method.

 

3. Advanced annotations

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

@SelectProvider

@InsertProvider

@UpdateProvider

@DeleteProvider

As the name implies, these advanced annotations are mainly used for dynamic SQL. Here, @SelectProvider is taken as an example. It mainly contains two annotation attributes, where type represents a tool class, and method represents a method of a tool class, which is used to return specific SQL.

@Mapper
public interface UserMapper {
   @SelectProvider(type = UserSqlProvider.class, method = "list222")
   List<User> list2();
}

The tool code is as follows:

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

4. Detailed tutorial

After understanding the above annotations, we use specific project cases to further consolidate the actual use of these annotations.

1. Introduce dependencies

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

<dependencies>
       <dependency> <!--添加Web依赖 -->
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>
       <dependency> <!--添加Mybatis依赖 -->
           <groupId>org.mybatis.spring.boot</groupId>
           <artifactId>mybatis-spring-boot-starter</artifactId>
           <version>1.3.1</version>
       </dependency>
       <dependency><!--添加MySQL驱动依赖 -->
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <scope>runtime</scope>
       </dependency>
       <dependency><!--添加Test依赖 -->
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
   </dependencies>

 

2. Add configuration

The main purpose here is to add data sources, configure camel case mapping and enable console printing of SQL logs. In the resource directory of the project, add application.yml configuration as follows:

spring:
 datasource:
   #连接MySQL
   url: jdbc:mysql://localhost:3306/socks?useSSL=false
   username: root
   password: root
   driver-class-name: com.mysql.jdbc.Driver

mybatis:
 configuration:
  #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
  map-underscore-to-camel-case: true

logging:
 level:
  #打印SQL信息
  com.hehe.mapper: debug

3. Write data layer code

Here we take the familiar user information as an example to write the UserMapper interface and the UserSqlProvider used in this case.

3.1 UserMapper

Add UserMapper interface for data query:

package com.hehe.mapper;
@Mapper
public interface UserMapper {
   /**
    * 方式1:使用注解编写SQL。
    */
   @Select("select * from t_user")
   List<User> list();

   /**
    * 方式2:使用注解指定某个工具类的方法来动态编写SQL.
    */
   @SelectProvider(type = UserSqlProvider.class, method = "listByUsername")
   List<User> listByUsername(String username);

   /**
    * 延伸:上述两种方式都可以附加@Results注解来指定结果集的映射关系.
    *
    * PS:如果符合下划线转驼峰的匹配项可以直接省略不写。
    */
   @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<User> listSample();

   /**
    * 延伸:无论什么方式,如果涉及多个参数,则必须加上@Param注解,否则无法使用EL表达式获取参数。
    */
   @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, a tool class used to generate SQL.

/**
* 主要用途:根据复杂的业务需求来动态生成SQL.
* <p>
* 目标:使用Java工具类来替代传统的XML文件.(例如:UserSqlProvider.java <-- UserMapper.xml)
*/
public class UserSqlProvider {
   /**
    * 方式1:在工具类的方法里,可以自己手工编写SQL。
    */
   public String listByUsername(String username) {
       return "select * from t_user where username =#{username}";
   }

   /**
    * 方式2:也可以根据官方提供的API来编写动态SQL。
    */
   public String getBadUser(@Param("username") String username, @Param("password") String password) {
       return new SQL() {
   
   {
           SELECT("*");
           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 entity class User

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

3.4 Add database records

Open the Navicat query window, and then only need 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 control layer code

package com.hehe.controller;

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

   @SuppressWarnings("all")
   @Autowired
   UserMapper userMapper;

   @GetMapping("list")
   public List<User> list() {
       return userMapper.list();
   }

   @GetMapping("list/{username}")
   public List<User> 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);
   }
}

5. Startup and test

After starting the project, visit http://localhost:8080/user/list to view the user list as follows:

Visit http://localhost:8080/user/list/admin to query the information of the user name admin:

Guess you like

Origin blog.csdn.net/qq_35860138/article/details/102677804