随笔 - 458  文章 - 0  评论 - 11  阅读 - 39万

MyBatis(3.2.3) - Handling enumeration types

MyBatis supports persisting enum type properties out of the box. Assume that the STUDENTS table has a column gender of the type varchar to store either MALE or FEMALE as the value. And, the Student object has a gender property that is of the type enum as shown in the following code:

public enum Gender {
    FEMALE,
    MALE;
}

 

By default, MyBatis uses EnumTypeHandler to handle enum type Java properties and stores the name of the enum value. You don't need any extra configuration to do this. You can use enum type properties just like primitive type properties as shown in the following code:

复制代码
public class Student {
    private Integer id;
    private String name;
    private String email;
    private PhoneNumber phone;
    private Address address;
    private Gender gender;
    
    //setters and getters
}
复制代码
<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
    insert into students(name,email,addr_id, phone,gender) values(#{name},#{email},#{address.addrId},#{phone},#{gender})
</insert>

When you execute the insertStudent statement, MyBatis takes the name of the Gender enum (FEMALE/MALE) and stores it in the GENDER column.

If you want to store the ordinal position of the enum instead of the enum name, you will need to explicitly configure it.

So if you want to store 0 for FEMALE and 1 for MALE in the gender column, you'll need to register EnumOrdinalTypeHandler in the mybatis-config.xml file.

<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.mybatis3.domain.Gender"/>

Be careful to use ordinal values to store in the DB. Ordinal values are assigned to enum values based on their order of declaration. If you change the declaration order in Gender enum, the data in the database and ordinal values will be mismatched.

 

posted on   huey2672  阅读(378)  评论(0编辑  收藏  举报
编辑推荐:
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 你所不知道的 C/C++ 宏知识
阅读排行:
· 不到万不得已,千万不要去外包
· C# WebAPI 插件热插拔(持续更新中)
· 会议真的有必要吗?我们产品开发9年了,但从来没开过会
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 如何打造一个高并发系统?
历史上的今天:
2015-03-01 ZooKeeper(3.4.5) - 开源客户端 Curator(2.7.0) 的简单示例
2015-03-01 ZooKeeper(3.4.5) - 原生 API 的简单示例
2015-03-01 ZooKeeper(3.4.5) - 配置伪集群模式
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示