mybatis学习之枚举typehandler

在绝大数的情况下,typeHandler因为枚举类而使用,MyBatis已经定义了两个类作为枚举类的支持,这两个类是

  • EnumOrdinalTypeHandler
  • EnumTypeHandler
    前者是按mybatis根据枚举数组下标索引的方式进行匹配的,它要求数据库返回一个整数作为其下标,它会根据下标找到对应的枚举类型,后者是EnumTypeHandler会把使用的名称转化为对应的枚举,具体的在实例在进行解释
    首先先来建立一个性别的枚举类-SexEnum
package com.learn.ssm.chapter4.enumeration;

public enum SexEnum {
    MALE(1,"男"),
    FEMALE(0,"女");

    
    private int id;
    private String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    //构造方法
    SexEnum(int id,String name){
        this.id=id;
        this.name=name;
    }
    public static SexEnum getSexById(int id){
        for(SexEnum sex:SexEnum.values()){
            if(sex.getId()==id){
                return sex;
//  返回male或者fmale,是为了后面的自定义的typehandler
            }
        }
        return null;
    }
//  public static void main(String[] args) {
//      SexEnum[] season1 = SexEnum.values();
//      System.out.println();
//      System.out.println(season1[0].getSexById(season1[0].getId()).getName());
//    // 枚举类的使用方法,values是枚举型数据的声明值,比如MALE,返回的是一个数组、
//  }
}

为了使用这个关于性别的枚举类,先创建一个pojo类

package com.learn.ssm.chapter3.pojo;

import com.learn.ssm.chapter4.enumeration.SexEnum;

public class User {
    private Long id;
    private String userName;
    private String password;
    private SexEnum sex;
//  枚举类的sex
    private String mobile;
    private String tel;
    private String email;
    private String note;

    /** setter and getter **/
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public SexEnum getSex() {
        return sex;
    }

    public void setSex(SexEnum sex) {
        this.sex = sex;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getNote() {
        return note;
    }

    public void setNote(String note) {
        this.note = note;
    }

}

数据库设计如下:


数据.png

设计表.png

EnumOrdinalTypeHandler

为了测试,可以创建一个UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learn.ssm.chapter3.mapper.UserMapper">
    <resultMap id="userMapper" type="user">
        <result property="id" column="id" />
        <result property="userName" column="user_name" />
        <result property="password" column="password" />
        <result property="sex" column="sex" 
        typeHandler="org.apache.ibatis.type.EnumOrdinalTypeHandler"/>
           <!--  typeHandler="com.learn.ssm.chapter4.typehandler.SexEnumTypeHandler"/> -->
        <!--  
        <result property="sex" column="sex" 
            typeHandler="org.apache.ibatis.type.EnumTypeHandler"/> 
        -->
        <!-- 
        <result property="sex" column="sex"  
            typeHandler="com.learn.ssm.chapter4.typehandler.SexEnumTypeHandler"/>
        -->
        <result property="mobile" column="mobile" />
        <result property="tel" column="tel" />
        <result property="email" column="email" />
        <result property="note" column="note" />
    </resultMap>
    <select id="getUser" resultMap="userMapper" parameterType="long">
      select id, user_name, password, sex, mobile, tel, email, note from t_user 
      where id = #{id}
    </select>
</mapper>

因为枚举类声明的顺序是:MALE(1,"男"),FEMALE(0,"女");
所以sex字段在数据库设计为1的时候,返回的结果是女性。mybatis自动把sex字段的值转为int类型,因为在执行EnumOrdinalTypeHandler是根据mybatis返回的数组索引进行匹配的,所以要求数据库返回的是一个整数,如果不是整数,会报错误


类型错误.png

测试类:

    private static void testTypeHandler() {
        Logger log = Logger.getLogger(chapter4Main.class);
        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionFactoryUtils.openSqlSession();
            UserMapper userMapper  = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.getUser(1L);
//          自带的EnumordinalTypeHandler和EnumTypehandler前置存储的是枚举的顺序号,后者是枚举实例名,但是有时候我们想用枚举的id来确定。这需要自定义枚举类typeHandler
            
            System.out.println("user的sex在这里"+user);
            System.out.println("user的sex在这里"+user.getSex());
            System.out.println(user.getSex().getName());
            System.out.println("userName这里"+user.getUserName());
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
    }

执行的日志


日志

EnumTypeHandler

EnumTypeHandler是根据数据库返回的字符串如“MALE”或者"FEMALE",进行Enum.valueOf(SexEnum.class,"MALE")转换,多以为了测试EnumTypeHandler的转换,我们把数据库的字段的sex字段修改为字符型(varchar(10))并把数据修改为FEMALE
注意修改UserMapper.xml中的tyopehandler为EnumTypeHandler

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.learn.ssm.chapter3.mapper.UserMapper">
    <resultMap id="userMapper" type="user">
        <result property="id" column="id" />
        <result property="userName" column="user_name" />
        <result property="password" column="password" />
        <result property="sex" column="sex" 
        typeHandler="org.apache.ibatis.type.EnumTypeHandler"/>
           <!--  typeHandler="com.learn.ssm.chapter4.typehandler.SexEnumTypeHandler"/> -->
        <!--  
        <result property="sex" column="sex" 
            typeHandler="org.apache.ibatis.type.EnumTypeHandler"/> 
        -->
        <!-- 
        <result property="sex" column="sex"  
            typeHandler="com.learn.ssm.chapter4.typehandler.SexEnumTypeHandler"/>
        -->
        <result property="mobile" column="mobile" />
        <result property="tel" column="tel" />
        <result property="email" column="email" />
        <result property="note" column="note" />
    </resultMap>
    <select id="getUser" resultMap="userMapper" parameterType="long">
      select id, user_name, password, sex, mobile, tel, email, note from t_user 
      where id = #{id}
    </select>
</mapper>

自定义枚举typeHandler

我们已经讨论了Mybatis内部提供的两种转换的typeHandler,但是他们有很大的局限性,更多的时候我们希望使用自定义的typeHandler,修改数据库为以下:


image.png

其中sex的数据类型改为int(10)
此时,按SexEnum的定义,sex=1为男性,sex=0为女性。为了满足这个规则,让我们自定义一个SexEnumTypeHandler

package com.learn.ssm.chapter4.typehandler;

import java.sql.CallableStatement;
import java.sql.JDBCType;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import com.learn.ssm.chapter4.enumeration.SexEnum;

public class SexEnumTypeHandler implements TypeHandler<SexEnum> {

    @Override
    public void setParameter(PreparedStatement ps, int i, SexEnum parameter,
            JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getId());
//      是使用typeHandler通过preparedStatment对象进行设置SQL参数的时候使用的具体方法,i是SQL的下标,parameter是参数,jdbcType是数据库类型
//  执行预编译sql
    }

    @Override
    public SexEnum getResult(ResultSet rs, String columnName)
            throws SQLException {
        int id = rs.getInt(columnName);
        return SexEnum.getSexById(id);
    }

    @Override
   public SexEnum getResult(ResultSet rs, int columnIndex) throws SQLException {
        int id = rs.getInt(columnIndex);
        return SexEnum.getSexById(id);
    }

    @Override
    public SexEnum getResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        int id = cs.getInt(columnIndex);
        return SexEnum.getSexById(id);
    }

}

然后修改UserMapper.xml中的

    <result property="sex" column="sex" 
        typeHandler="com.learn.ssm.chapter4.typehandler.SexEnumTypeHandler"/>```
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,783评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,360评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 142,942评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,507评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,324评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,299评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,685评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,358评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,652评论 1 293
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,704评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,465评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,318评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,711评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,991评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,265评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,661评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,864评论 2 335

推荐阅读更多精彩内容