MyBatis支持持久化enum类型属性。假设t_user表中有一列gender(性别)类型为 varchar2(10),存储 MALE 或者 FEMALE 两种值。并且,User对象有一个enum类型的gender 属性,如下所示:

public enum Gender {
MALE,FEMALE;
}

默认情况下MyBatis使用EnumTypeHandler来处理enum类型的Java属性,并且将其存储为enum值的名称。我们不需要为此做任何额外的配置。可以像使用基本数据类型属性一样使用enum类型属性,如下:

create table t_user(
id number primary key,
name varchar2(50),
gender varchar2(10)
);
public class User{
private Integer id;
private String name;
private Gender gender; //setters and getters
}

映射文件:

<insert id="insertUser" parameterType="User">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select my_seq.nextval from dual
</selectKey>
insert into t_user(id,name,gender)
values(#{id},#{name},#{gender})
</insert>

映射接口:

public interface XxxxMapper{
int insertUser(User user);
}

测试方法:

@Test
public void test_insertUser(){ SqlSession sqlSession = null;
try {
sqlSession = MyBatisSqlSessionFactory.openSession(); SpecialMapper mapper = sqlSession.getMapper(SpecialMapper.class);
User user = new User("tom",Gender.MALE); mapper.insertUser(user); sqlSession.commit();
} catch (Exception e) {
e.printStackTrace();
}
}

当执行insertStudent语句的时候MyBatis会取Gender枚举(FEMALE/MALE)的名称,存储到GENDER列中。

如果你想存储FEMALE为0,MALE为1到gender列中,需要在mybatis-config.xml文件中配置专门的类型处理器,并指定它处理的枚举类型是哪个。
<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.briup.special.Gender"/>

EnumOrdinalTypeHandler这是个类型处理器,源码中有个set方法就是在帮助我们存值,源码如下

/**
* Copyright 2009-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ibatis.type; import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; /**
* @author Clinton Begin
*/
public class EnumOrdinalTypeHandler<E extends Enum<E>> extends BaseTypeHandler<E> { private final Class<E> type;
private final E[] enums; public EnumOrdinalTypeHandler(Class<E> type) {
if (type == null) {
throw new IllegalArgumentException("Type argument cannot be null");
}
this.type = type;
this.enums = type.getEnumConstants();
if (this.enums == null) {
throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
}
} @Override
public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
ps.setInt(i, parameter.ordinal());
} @Override
public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
int i = rs.getInt(columnName);
if (rs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
} @Override
public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
int i = rs.getInt(columnIndex);
if (rs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
} @Override
public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
int i = cs.getInt(columnIndex);
if (cs.wasNull()) {
return null;
} else {
try {
return enums[i];
} catch (Exception ex) {
throw new IllegalArgumentException("Cannot convert " + i + " to " + type.getSimpleName() + " by ordinal value.", ex);
}
}
} }

枚举类型的【顺序值】是根据enum中的声明顺序赋值的。如果改变了Gender里面对象的声明顺序,则数据库存储的数据和此顺序值就不匹配了。

mybatis 处理枚举类型的更多相关文章

  1. MyBatis里字段到枚举类型的转换/映射

    一.简介 我们在用MyBatis里,很多时间有这样一个需求:bean里有个属性是枚举,在DB存储时我们想存的枚举的代号,从DB拿出来时想直接映射成目标枚举类型,也即代号字段与Java枚举类的相互类型转 ...

  2. MyBatis对于Java对象里的枚举类型处理

    平时咱们写程序实体类内或多或少都会有枚举类型属性,方便嘛.但是mybatis里怎么处理他们的增删改查呢? 要求: 插入的时候,会用枚举的定义插入数据库,我们希望在数据库中看到的是数字或者其他东西: 查 ...

  3. mybatis 枚举类型使用

    一.首先定义接口,提供获取数据库存取的值得方法,如下: public interface BaseEnum { int getCode(); } 二.定义mybatis的typeHandler扩展类, ...

  4. mybatis枚举类型处理器

    1. 定义枚举值的接口 public abstract interface ValuedEnum { int getValue(); } 所有要被mybatis处理的枚举类继承该接口 2. 定义枚举类 ...

  5. MyBatis(八):Mybatis Java API枚举类型转化的用法

    最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习: 1)Java API处理一对多.多对一的用法: 2)增.删.改.查的用法: 3) ...

  6. 解决mybatis使用枚举的转换

    解决mybatis使用枚举的转换 >>>>>>>>>>>>>>>>>>>>> ...

  7. mybatis-枚举类型的typeHandler&自定义枚举类型typeHandler

    MyBatis内部提供了两个转化枚举类型的typeHandler给我们使用. org.apache.ibatis.type.EnumTypeHandler 是使用枚举字符串名称作为参数传递的 org. ...

  8. Mybatis的枚举处理器

    Mybatis有两个默认枚举处理器 EnumOrdinalTypeHandler EnumTypeHandler 自定义枚举 EnumOrdinalTypeHandler 这个处理器负责将pojo里面 ...

  9. mybatis自定义枚举转换类

    转载自:http://my.oschina.net/SEyanlei/blog/188919 mybatis提供了EnumTypeHandler和EnumOrdinalTypeHandler完成枚举类 ...

随机推荐

  1. 剑指offer——丑数(c++)

    题目描述只包含质因子2.3和5的数称作丑数(UglyNumber).例如6.8都是丑数,但14不是,因为它包含质因子7,习惯上我们把1当做是第一个丑数.求按从小到大的顺序的第N个丑数. 思路:1.逐个 ...

  2. ollydbg调试PE文件

    ollydbg项目地址:http://www.ollydbg.de/ 将exe文件打开到ollydbg项目中,就会直接停到"入口点"地址处,通过View->Memory Ma ...

  3. qemu的动态翻译机制

    qemu的作者在QEMU, a Fast and Portable Dynamic Translator一文提到了qemu的动态翻译机制, 大致可以总结为如下过程: 目标代码中的一条指令 | |--( ...

  4. HTML中<frameset>标签不显示的问题

    啥都不说,先上代码 <html> <head> <title>index</title> <meta content = 'text/html'; ...

  5. Rollei SL66 使用说明

    根据记忆,并用不规范的语言描述我对sl66的使用心得:一.上卷1.用摇把顺时针转到12点位置,再退回3点位置:2.安插刀:3.后背上方按钮向右拨,打开后背:4.取出,装卷,再放入:5.转动后背上旋钮, ...

  6. 构造+数位dp

    参考博客: 题目链接: 题意:给定正整数a,b,k,你的任务是在所有满足a<=n<=b中的整数n中,统计有多少个满足n自身是k的倍数,且n的各位数字之和也是k的倍数. [思路] 这种题的固 ...

  7. Python的序列化和反序列化

    序列化是将dict---->str 反序列化是将str---->dict import jsonresult1 = json.dumps({'a': 1, 'b': 2}) #序列化res ...

  8. vim - Vi IMproved, 一个程序员的文本编辑器

    总览 (SYNOPSIS) vim [options] [file ..] vim [options] - vim [options] -t tag vim [options] -q [errorfi ...

  9. Sql Server的内存策略

    最近碰到有人问我在使用sql server的时候,内存突然升高,但是没有log日志进行详细的调查,有没有什么解决办法. 在此我经过一番查询,发现了2种能够对内存进行一定优化限制的方法. 在数据库上点击 ...

  10. fedora 28 winscp链接不上

    systemctl restart sshd.service //启动sshd服务 systemctl stop firewalld //关闭防火墙 /etc/selinux/config //关闭s ...