1 introduction

Tips you can get from reading this article:

  1. A custom enumerated class with a Chinese name
  2. Refer to a Java class or enumeration in Mybatis’ WHERE condition instead of using dead-written values

Skills you need to master in advance:

  1. Java 8
  2. Mybatis

2. Preset Scenarios

There is a user information table T_user in the system, in which the field that records gender is gender. We need to write a method to query all female users

Enumeration is required for gender. 1 is male, 2 is female, and -1 is unknown

The simple query SQL is as follows:

select id, name, gender, email from t_user where gender = 2
Copy the code

However, if the above SQL is used directly, there will be some problems: if the value of female in the gender enumeration is changed from 2 to 88 later, this SQL should be modified in addition to the enumeration itself

How can data in MyBatis always reference enumerations in Java?

3 Solution

3.1 Creating a Custom enumeration

First, we create an enumeration interface with a Chinese name, Valuenameen.java:

public interface ValueNameEnum extends Serializable {
    /** * gets the enumeration value **@returnEnumeration values * /
    @JsonValue
    int getValue(a);
​
     /** * gets the enumeration name **@returnEnumeration name */
    String getName(a);
    
}
Copy the code

Create Gender enumeration gender.java:

public enum Gender implements ValueNameEnum {
    MAN(1."Men"),
    WOMAN(2."Women");
    
    private int value;
    private int name;
    
    Gender(int value, int name) {
        this.value = value;
        this.name = name;
    }
    
    @Override
    public int getValue(a) {
      return value;
    }
    
    @Override
    public String getName(a) {
      returnname; }}Copy the code

3.2 Writing MyBatis XML

MyBatis XML file:

<select id="listWomanUsers" resultType="cn.houtaroy.test.entities.UserEntity">
    select id, name, gender, email from t_user where gender = 2
</select>
Copy the code

Next change 2 to reference the value of the enumeration:

<select id="listWomanUsers" resultType="cn.houtaroy.test.entities.UserEntity">
    select id, name, gender, email from t_user where gender = '${@[email protected]}'
</select>
Copy the code

${} is a direct replacement

@className@method(args) is the static method of the calling class, and @className@field is the static property of the calling class

Enumeration uses the @enumeration class @enumeration.value

3.3 small pit

There is a special case where enumerations are inner classes, such as Gender in UserEntity:

public class UserEntity {
    private String id;
    private Gender gender;
    
    public enum Gender implements ValueNameEnum {
        / /... Enumeration code}}Copy the code

This kind of situation if we write into: ${@ [email protected]}, will quote cannot resolve the enumeration of error

This is where we need to use$, which means an inner class call:[email protected]