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.
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 现代计算机视觉入门之:什么是图片特征编码
· .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) - 配置伪集群模式