mybatis 处理枚举类型
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 处理枚举类型的更多相关文章
- MyBatis里字段到枚举类型的转换/映射
一.简介 我们在用MyBatis里,很多时间有这样一个需求:bean里有个属性是枚举,在DB存储时我们想存的枚举的代号,从DB拿出来时想直接映射成目标枚举类型,也即代号字段与Java枚举类的相互类型转 ...
- MyBatis对于Java对象里的枚举类型处理
平时咱们写程序实体类内或多或少都会有枚举类型属性,方便嘛.但是mybatis里怎么处理他们的增删改查呢? 要求: 插入的时候,会用枚举的定义插入数据库,我们希望在数据库中看到的是数字或者其他东西: 查 ...
- mybatis 枚举类型使用
一.首先定义接口,提供获取数据库存取的值得方法,如下: public interface BaseEnum { int getCode(); } 二.定义mybatis的typeHandler扩展类, ...
- mybatis枚举类型处理器
1. 定义枚举值的接口 public abstract interface ValuedEnum { int getValue(); } 所有要被mybatis处理的枚举类继承该接口 2. 定义枚举类 ...
- MyBatis(八):Mybatis Java API枚举类型转化的用法
最近工作中用到了mybatis的Java API方式进行开发,顺便也整理下该功能的用法,接下来会针对基本部分进行学习: 1)Java API处理一对多.多对一的用法: 2)增.删.改.查的用法: 3) ...
- 解决mybatis使用枚举的转换
解决mybatis使用枚举的转换 >>>>>>>>>>>>>>>>>>>>> ...
- mybatis-枚举类型的typeHandler&自定义枚举类型typeHandler
MyBatis内部提供了两个转化枚举类型的typeHandler给我们使用. org.apache.ibatis.type.EnumTypeHandler 是使用枚举字符串名称作为参数传递的 org. ...
- Mybatis的枚举处理器
Mybatis有两个默认枚举处理器 EnumOrdinalTypeHandler EnumTypeHandler 自定义枚举 EnumOrdinalTypeHandler 这个处理器负责将pojo里面 ...
- mybatis自定义枚举转换类
转载自:http://my.oschina.net/SEyanlei/blog/188919 mybatis提供了EnumTypeHandler和EnumOrdinalTypeHandler完成枚举类 ...
随机推荐
- Codeforces ~ 1009C ~ Annoying Present (贪心)
题意 一个长度为n的数组(初始全为0),进行m次操作. 操作:给你x,d,你任意挑选一个 i (1~n),每个数字加上 x+|i-j|*d( j 表示对应数字的下标) 问m次操作后的最大算术平均值为多 ...
- GitHub 万星推荐:黑客成长技术清单
GitHub 万星推荐:黑客成长技术清单 导语:如果你需要一些安全入门引导,“Awesome Hacking”无疑是最佳选择之一. 最近两天,在reddit安全板块和Twitter上有个GitHub项 ...
- js读取json数据
{ "code": 0, "msg": null, "data": { "pageNum": 1, "page ...
- PAT_A1012#The Best Rank
Source: PAT A1012 The Best Rank (25 分) Description: To evaluate the performance of our first year CS ...
- Linux 下通过mail命令发送邮件
mail -s "测试" 1968089885@foxmail.com 需要先配置smtp服务器
- js登陆验证错误不刷新页面
验证函数返回 false;返回到onclickonclick 其实也是一个函数.. 所以需要加 return;
- 在linux 下查询某个进程被那个程序占用
ps -ef|grep pid ps -aux | grep pid 清除linux 缓存: echo 1 > /proc/sys/vm/drop_caches
- &与&&,|与||的区别
今天在做leetcode的时候,遇到了运算符的不同而导致结果不一致的问题.记录一下提醒自己 中文名称与英文名称 &:按位与(Bitwise and) &&:逻辑与(logica ...
- eclipse search只能打开一个文件
通过search找到的文件只能打开一个.以前search打开的那个文件就自动关闭了,找不到了.解决办法: window-preferences-general-search找到第一行的一个选项 re ...
- 上线出现[x86_64, i386]
echo "Target architectures: $ARCHS" APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}&quo ...