使用 MyBatis-Plus 实现 PO 对象枚举类型与 JdbcType 互相转换

1. 相关版本说明

Spring Boot 版本:2.2.2.RELEASE

MyBatis-Plus 版本:3.3.0

2. 模型准备

  • 2.1 User PO
@Data
@TableName("t_user")
public class User {
    /**
     * ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 用户名
     */
    @TableField(value = "name", jdbcType = JdbcType.VARCHAR)
    private String name;

    /**
     * 年龄
     */
    @TableField(value = "age", jdbcType = JdbcType.INTEGER)
    private Integer age;

    /**
     * 性别
     */
    @TableField(value = "gender", jdbcType = JdbcType.INTEGER)
    private Gender gender;

    /**
     * 学历
     */
    @TableField(value = "education", jdbcType = JdbcType.INTEGER)
    private Education education;

    /**
     * 生日
     */
    @TableField(value = "birthday", jdbcType = JdbcType.DATE)
    private Date birthday;
}
  • 2.2 Gender enum
public enum Gender {
    /**
     * 女性
     */
    FEMALE(0),

    /**
     * 男性
     */
    MALE(1),

    /**
     * 其他
     */
    OTHER(2);
    
    @Getter
    private final int value;

    Gender(int value) {
        this.value = value;
    }
}
  • 2.3 Education enum
public enum Education {
    /**
     * 本科
     */
    UNDERGRADUATE(0),

    /**
     * 硕士
     */
    MASTER(1),

    /**
     * 博士
     */
    DOCTOR(2);

    @Getter
    private final int value;

    Education(int value) {
        this.value = value;
    }
}

3. 实现

defaultEnumTypeHandler

  • 类型:Class<? extends TypeHandler
  • 默认值:org.apache.ibatis.type.EnumTypeHandler

默认枚举处理类,如果配置了该属性,枚举将统一使用指定处理器进行处理

  • org.apache.ibatis.type.EnumTypeHandler : 存储枚举的名称
  • org.apache.ibatis.type.EnumOrdinalTypeHandler : 存储枚举的索引
  • com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler : 枚举类需要实现IEnum接口或字段标记@EnumValue注解.(3.1.2以下版本为EnumTypeHandler)
  • com.baomidou.mybatisplus.extension.handlers.EnumAnnotationTypeHandler: 枚举类字段需要标记@EnumValue注解
  • 3.2 修改配置

可以看出 Mybatis-Plus 为我们提供了3种实现,MybatisEnumTypeHandler 这种实现灵活性较高,可以满足我们的要求,因此我们可以配置 defaultEnumTypeHandler 的 实现为MybatisEnumTypeHandler。

注意: Mybatis 3.4.5 后才提供org.apache.ibatis.session.Configuration#setDefaultEnumTypeHandler()

mybatis-plus.configuration.default-enum-type-handler=com.baomidou.mybatisplus.extension.handlers.MybatisEnumTypeHandler
  • 3.3 实现一:枚举类实现 IEnum 接口的方式,改造 Gender 枚举类为
public enum Gender implements IEnum<Integer> {

    /**
     * 女性
     */
    FEMALE(0),

    /**
     * 男性
     */
    MALE(1),

    /**
     * 其他
     */
    OTHER(2);

    private final int value;

    Gender(int value) {
        this.value = value;
    }

    @Override
    public Integer getValue() {
        return this.value;
    }
}
  • 3.4 实现二: 枚举字段标记 @EnumValue 方式,改造 Education 枚举类为
public enum Education {

    /**
     * 本科
     */
    UNDERGRADUATE(0),

    /**
     * 硕士
     */
    MASTER(1),

    /**
     * 博士
     */
    DOCTOR(2);

    @Getter
    @EnumValue
    private final int value;

    Education(int value) {
        this.value = value;
    }
}
  • 3.5 测试验证

    UserMapper#insert(T entity) 向数据库插入数据

@SpringBootApplication
public class SpringbootMybatisplusApplication implements ApplicationRunner {

    public static void main(String[] args) {
        new SpringApplicationBuilder()
                .sources(SpringbootMybatisplusApplication.class)
                .web(WebApplicationType.NONE)
                .bannerMode(Banner.Mode.OFF)
                .run(args);
    }

    @Autowired
    UserMapper userMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        testInsert();
    }

    private void testInsert() {
        User user = new User();
        user.setName("test");
        user.setAge(25);
        user.setGender(Gender.MALE);
        user.setEducation(Education.UNDERGRADUATE);
        user.setBirthday(new Date());
        userMapper.insert(user);
        System.out.println(user);
    }
}

运行程序,成功向数据库插入记录,PO 对象枚举类型转换为 JdbcType 成功!

​ 使用 UserMapper#selectList(null) 查询数据库记录

@Override
public void run(ApplicationArguments args) throws Exception {
// testInsert();
testList();
}

private void testList() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}

运行程序,成功打印出 User 记录信息,JdbcType 转换为 PO 对象枚举类型 成功!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用 MyBatis-Plus 实现 CRUD 操作,首先需要在项目中引入 MyBatis-Plus 的依赖: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.1</version> </dependency> ``` 然后,在 `application.yml` 中配置数据库连接信息和 MyBatis-Plus 配置: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: mapper-locations: classpath:mapper/*.xml configuration: map-underscore-to-camel-case: true ``` 接着,定义实体类和 Mapper 接口。这里以一个 `User` 实体类为例: ```java @Data public class User { private Long id; private String name; private Integer age; private String email; } public interface UserMapper extends BaseMapper<User> { } ``` `UserMapper` 集成自 `BaseMapper`,这样就可以直接使用 MyBatis-Plus 提供的通用 CRUD 方法了。例如,插入数据: ```java @Autowired private UserMapper userMapper; public void insertUser(User user) { userMapper.insert(user); } ``` 查询数据: ```java public User getUserById(Long id) { return userMapper.selectById(id); } ``` 更新数据: ```java public void updateUser(User user) { userMapper.updateById(user); } ``` 删除数据: ```java public void deleteUserById(Long id) { userMapper.deleteById(id); } ``` 总之,MyBatis-Plus 为我们提供了很多便捷的方法,可以大大减少我们的编码量,提高开发效率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值