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完成枚举类 ...
随机推荐
- UDP 协议解析 - 1
目录 1. 概述 2. UDP 的主要特点 3. UDP 的首部格式 3. UDP 校验和 3.1 伪首部 3.2 UDP 校验和计算方法 [参考文献] 1. 概述 用户数据报协议(UDP,User ...
- Java8 时间调节器
TemporalAdjuster 是做日期数学计算.例如,要获得“本月第二个星期六”或“下周二”. 让我们来看看他们的操作. 选择使用任何编辑器创建以下java程序在 C:/> JAVA Jav ...
- 问题:Error running 'lugia-web': Address loaclhost:1099 is already in use
解决方法:cmd输入下面命令: 第一步: netstat -ano|findstr 1099 找到对应的pid 为3576.(每次不一样). 第二步:taskkill -f -pid 3576
- linux学习的任督二脉-进程调度和内存管理
转自 宋宝华老师的博客原文:https://blog.csdn.net/21cnbao/article/details/77505330 内功心法 学习或遇到问题时,反过来主动思考如果我是设计者,我会 ...
- JAVA集合--Iterator接口
本文首发于cartoon的博客 转载请注明出处:https://cartoonyu.github.io/cartoon-blog 上一篇文章中我在集合元素的遍历中已经有涉及到I ...
- D题 Robots 【期望】
Robots Given a directed graph with no loops which starts at node 11 and ends at node nn.There is a r ...
- URL&HTTP协议&GET请求&POST请求
1.什么是URL URL的全称是Uniform Resource Locator(统一资源定位符) 通过1个URL,能找到互联网上唯一的1个资源 URL就是资源的地址.位置,互联网上的每个资源都有一个 ...
- Unity中嵌入网页插件Embedded Browser2.1.0
背景 最近刚换了工作,新公司不是做手游的,一开始有点抵触,总觉得不是做游戏自己就是跨行了,认为自己不对口,但是慢慢发现在这可以学的东西面很广,所以感觉又到了打怪升级的时候了,老子就在这进阶了. 一进公 ...
- wpf mvvm datagrid 中button绑定命令方法
<DataGridTemplateColumn Header="设备状态" IsReadOnly="True" Width="150" ...
- 解决 Onenote 默认全角输入的一种解决办法(输入法已经设置为默认半角)
环境说明:Windows 7 x64 Ultimate SP1, QQ 拼音输入法 6.1(5306),Onenote 2016 x64 问题描述:每次打开Onenote,在输入法已经设置为默认半角的 ...