A common enumeration
To solve the complicated configuration, so mybatis elegant use of enumerated attribute!
From the
3.1.0
beginning, it can be configured to scan the default class enumeration process Enumeration common configuration is omitted default configuration Enumeration
Upgrade Instructions:
3.1.0
The following version changed the original default behavior when you upgrade an enumeration to set the defaultEnumOrdinalTypeHandler
Entities use native enum
other instructions:
Configuration list packet scanning time can be registered in advance using the comment cache enumeration
Recommended:
That implement
IEnum
interface
Recommended
defaultEnumTypeHandler
Enumeration process using annotations
Recommended
typeEnumsPackage
Notes enumeration process and
IEnum
interface
Recommended
typeEnumsPackage
Mix with the native enum
Must be configured
defaultEnumTypeHandler
withtypeEnumsPackage
Affirming General enumerated attribute
Method 1: Use @EnumValue comment enumerated attribute complete example
public enum GradeEnum { a PRIMARY ( . 1, "Primary"), SECONDORY (2, "Middle"), HIGH (3, "high school" ); GradeEnum ( int code, String descp) { the this .code = code; the this . = descp descp; } @EnumValue // value of the flag is the data stock code Private Final int code; // . . . }
Second way: enumerated attribute, IEnum interfaces implemented as follows:
public enum AgeEnum implements IEnum<Integer> { ONE(1, "一岁"), TWO(2, "二岁"), THREE(3, "三岁"); private int value; private String desc; @Override public Integer getValue() { return this.value; } }
Entity attribute the enum
public class the User { / ** * Name * database fields: name VARCHAR (20 is) * / Private String name; / ** * Age, the enumeration process IEnum interface * database fields: the INT Age (. 3) * / Private AgeEnum Age ; / ** * grade native enum (with { @link com.baomidou.mybatisplus.annotation.EnumValue}): * database fields: the INT Grade (2) * / Private GradeEnum Grade; }
Second code
-
pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/p6spy/p6spy --> <dependency> <groupId>p6spy</groupId> <artifactId>p6spy</artifactId> <version>3.8.0</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.49</version> <scope>test</scope> </dependency> <!-- for testing --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
-
application.yml
the Spring: the DataSource: Driver - class - name: com.p6spy.engine.spy.P6SpyDriver url: jdbc: P6Spy: h2: tcp: // 192.168.180.115:19200/~/mem/test username: root password: the Test # MP configure the mybatis - PLUS: of the type -enums- Package Penalty for : com.mp.sampleenum.enums the configuration: # 3.0 before .8 default version of the problem will enumerate registered as EnumOrdinalTypeHandler, this is the wrong way, the default is org.apache.ibatis. type.EnumTypeHandler # If the project in a manner consistent use IEnum entities or annotations can be configured to com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler, also omitted the above type -enums- Package Penalty for configuration # Configuration of the type -enums- Package Penalty for enumeration process only comment on the way the cache can be loaded in advance. Default - enum The -type-Handler: org.apache.ibatis.type.EnumOrdinalTypeHandler
-
Configuration class
@Configuration @MapperScan("com.mp.sampleenum.mapper") public class MybatisPlusConfig { }
-
Entity class
@EqualsAndHashCode (= callSuper to true ) @Data @Accessors (catena alberghiera = to true ) public class the User the extends the BaseEntity { Private String name; Private String In Email; / ** * IEnum enumeration process interface * / Private AgeEnum Age; / ** * native enumeration: enumeration value default order: 0: MALE,. 1: FEMALE * / Private GenderEnum Gender; / ** * native enum (with { @link com.baomidou.mybatisplus.annotation. EnumValue}): * Value should be the annotation of the database attributes * / @JSONField (serialzeFeatures = SerializerFeature.WriteEnumUsingToString) Private GradeEnum Grade; Private the UserState userState; } @Data @Accessors (catena alberghiera = to true ) public class the BaseEntity { Private Long ID ; }
-
enumerate
@Getter public enum AgeEnum implements IEnum<Integer> { ONE(1, "一岁"), TWO(2, "二岁"), THREE(3, "三岁"); private final int value; private final String desc; AgeEnum(final int value, final String desc) { this.value = value; this.desc = desc; } @Override public Integer getValue() { return value; } } public enum GenderEnum { MALE, FEMALE; } @Getter //@JSONType(serializeEnumAsJavaBean = true) public enum GradeEnum { PRIMARY(1, "小学"), SECONDORY(2, "中学"), HIGH(3, "高中"); GradeEnum(int code, String descp) { this.code = code; this.descp = descp; } //@EnumValue private final int code; @EnumValue private final String descp; } @Getter public enum UserState implements IBaseEnum<Integer> { ACTIVE(1, "A"), INACTIVE(2, "I"); private final int state; private final String descp; UserState(int state, String descp) { this.state = state; this.descp = descp; } @Override public Integer getValue() { return state; } @Override public String getDescription() { return descp; } } public interface IBaseEnum<T extends Serializable> extends IEnum<T>{ String getDescription(); }
Note: Recommended annotated way, GradeEnum want to insert this enumeration of type String, be serialized with Fastjson.
-
Test category
@SpringBootTest class SampleEnumApplicationTests { @Resource private UserMapper mapper; @Test public void insert() { User user = new User(); user.setName("K神"); user.setAge(AgeEnum.ONE); user.setGrade(GradeEnum.HIGH); user.setGender(GenderEnum.MALE); user.setEmail("[email protected]"); user.setUserState(UserState.ACTIVE); Assert.assertTrue(mapper.insert(user) > 0); // 成功直接拿会写的 ID System.err.println("\n插入成功 ID 为:" + user.getId()); List<User> list = mapper.selectList(null); for (User u : list) { System.out.println(u); Assert.assertNotNull("age should not be null", u.getAge()); if (u.getId().equals(user.getId())) { Assert.assertNotNull("gender should not be null", u.getGender()); Assert.assertNotNull("grade should not be null", u.getGrade()); } } } @Test public void delete() { Assert.assertTrue(mapper.delete(new QueryWrapper<User>() .lambda().eq(User::getAge, AgeEnum.TWO)) > 0); } @Test public void update() { Assert.assertTrue(mapper.update(new User().setAge(AgeEnum.TWO), new QueryWrapper<User>().eq("age", AgeEnum.THREE)) > 0); } @Test public void select() { User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 2)); Assert.assertEquals("Jack", user.getName()); Assert.assertTrue(AgeEnum.THREE == user.getAge()); //#1500 github: verified ok. Not a bug List<User> userList = mapper.selectList(new QueryWrapper<User>().lambda().eq(User::getUserState, UserState.ACTIVE)); Assert.assertEquals(3, userList.size()); Optional<User> userOptional = userList.stream() .filter(x -> x.getId() == 1) .findFirst(); userOptional.ifPresent(user1 -> Assert.assertTrue(user1.getUserState() == UserState.ACTIVE)); } }