content
1. Add fields to the data table
2. Create a generic enumeration type
3. Add corresponding attributes to the entity class
4. Configure the package where the scan general enumeration is located
Some field values in the table are fixed, such as gender (male or female), at this time we can use the general enumeration of MyBatis-Plus to achieve
1. Add fields to the data table
2. Create a generic enumeration type
@Getter // 生成getter方法
public enum SexEnum {
MALE(1, "男"),
FEMALE(2, "女");
@EnumValue // 将注解所标识的属性的值存储到数据库中
private Integer sex;
private String sexName;
SexEnum(Integer sex, String sexName) {
this.sex = sex;
this.sexName = sexName;
}
}
3. Add corresponding attributes to the entity class
@Data
@AllArgsConstructor
@NoArgsConstructor
//@TableName("t_user") // 设置该实体类所对应的表的表明
public class User {
// 将属性对应的字段设定为主键
// value属性用于指定主键的字段
// type属性用于设置主键的生成策略
@TableId(value = "uid", type = IdType.AUTO)
private Long id;
// 设置属性所对应的字段名
@TableField("user_name")
private String name;
private Integer age;
private String email;
private SexEnum sex;
@TableLogic
private Integer isDeleted;
}
4. Configure the package where the scan general enumeration is located
Configure the package where the scan generic enumeration is located in application.yml
mybatis-plus:
type-enums-package: com.zyj.mybatisplus.enums # 配置扫描通用枚举所在的包
5. Test
testing method:
@SpringBootTest
public class MyBatisPlusEnumTest {
@Autowired
UserMapper userMapper;
@Test
public void test(){
User user = new User();
user.setName("admin");
user.setAge(33);
user.setSex(SexEnum.MALE);
int ret = userMapper.insert(user);
System.out.println("ret = " + ret);
}
}
Output result:
==> Preparing: INSERT INTO t_user ( user_name, age, sex ) VALUES ( ?, ?, ? )
==> Parameters: admin(String), 33(Integer), 1(Integer)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15dc339f]
ret = 1