5.8 mybatis之EnumTypeHandler详细使用

本文介绍了如何在Java中使用枚举类型与数据库进行交互,包括将枚举数据插入数据库和从数据库查询到枚举对象,以及EnumTypeHandler在MyBatis中的默认使用和配置。
摘要由CSDN通过智能技术生成


在 Java 中,枚举类型是一种特殊的类,当我们在数据库和 Java 对象之间进行映射时,通常需要将数据库中的某个字段(如字符串或数字)映射到 Java 枚举类型上,或者更新插入数据库时,需要把java的枚举类型映射到数据库字段上,这就需要一种机制来在两者之间建立映射关系。EnumTypeHandler 就是这样一个机制,它能够帮助我们完成这一任务。

EnumTypeHandler的使用很简单,或者你没有刻意去使用,mybatis在枚举映射时也是默认使用了EnumTypeHandler类型处理机制进行处理枚举映射的,为什么这么说呢?因为在mybatis的setting配置中有个defaultEnumTypeHandler参数,是为mybatis处理枚举映射指定的类型转换机制的,如下所示,指定了EnumTypeHandler类型处理机制,即使你不配置下面的枚举转换机制,mybatis也是默认使用的EnumTypeHandler类型转换机制。当然你也可以使用其他类型的枚举转换机制或者自定义枚举转换机制,然后在下面显示指定。

<settings>
    <setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumTypeHandler"/>
</settings>

下面我们看下EnumTypeHandler具体用法

1. 把java中枚举数据插入到数据库中

以如下库表PERSON为例
在这里插入图片描述
对应的java的Person类为

package com.lzj.bean;

public class Person {
    private int id;
    private String name;
    private Enum<SexEnum> sex;
    private int age;
    //省略get/set/toString
 }

对应的SexEnum枚举类如下所示

package com.lzj.bean;

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

    private String description;

    private SexEnum(String description){
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "SexEnum{" +
                "description='" + description + '\'' +
                '}';
    }
}

对应的Dao接口为

package com.lzj.dao;

import com.lzj.bean.Person;

import java.util.List;

public interface PersonDao {
    public int insert(Person person);
}

对应的mapper中SQL为

<insert id="insert" parameterType="com.lzj.bean.Person" useGeneratedKeys="true" keyProperty="id" keyColumn="person_id">
    insert into PERSON(person_name, person_sex, person_age) values(#{name},#{sex},#{age});
</insert>

修改mybatis配置文件添加defaultEnumTypeHandler参数,并指定EnumTypeHandler,当然也可以配置,因为默认就是用的EnumTypeHandler枚举类型转换机制。

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumTypeHandler"/>
</settings>

下面执行下面测试案例,向数据库中插入一条数据

public void sqlSessionTest1(){
    SqlSessionFactory factory = mybatisUtil.getFactory();
    SqlSession sqlSession = factory.openSession(true);  //true表示自动提交
    Person person = new Person();
    person.setAge(25);
    person.setSex(SexEnum.MALE);
    person.setName("Tom");
    sqlSession.insert("com.lzj.dao.PersonDao.insert", person);
    System.out.println("自增逐渐为:" + person.getId());
}

最后再重新查数据库如下所示,发现已经向数据库中又插入了一条Tom的数据,并且插入的person_sex为MALE。说明EnumTypeHandler是直接把数据库中值直接和JAVA钟枚举的属性名直接进行映射的。
在这里插入图片描述

2. 把数据库中值查询到java对象中

还是以上面为例,查询peson_id>5的所有数据映射到Person类对应的对象中

对应的mapper的SQL为,注意要为sex属性指定javaType类型

<resultMap id="resultMap1" type="com.lzj.bean.Person">
    <result column="PERSON_ID" property="id"></result>
    <result column="PERSON_NAME" property="name"></result>
    <result column="PERSON_SEX" property="sex" javaType="com.lzj.bean.SexEnum"></result>
    <result column="PERSON_AGE" property="age"></result>
</resultMap>
<select id="select1" resultMap="resultMap1">
    select * from PERSON where PERSON_ID > #{personId}
</select>

对应的dao接口为

public interface PersonDao {
    public List<Person> select1(int personId);
}

然后执行下面查询案例

public void sqlSessionTest2(){
    SqlSessionFactory factory = mybatisUtil.getFactory();
    SqlSession sqlSession = factory.openSession(true);  //true表示自动提交
    List<Person> persons = sqlSession.selectList("com.lzj.dao.PersonDao.select1", 5);
    System.out.println(persons);
    sqlSession.close();
}

输出结果如下所示,说明数据库中数据可以正常映射到Person对应的对象中。

Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 2259527.
==>  Preparing: select * from PERSON where PERSON_ID > ? 
==> Parameters: 5(Integer)
<==    Columns: person_id, person_name, person_age, person_sex
<==        Row: 13, Jerry, 20, FEMALE
<==        Row: 14, Tom, 25, MALE
<==      Total: 2
[Person{id=13, name='Jerry', sex=SexEnum{description='女性'}, age=20}, Person{id=14, name='Tom', sex=SexEnum{description='男性'}, age=25}]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@227a47]
Returned connection 2259527 to pool.
  • 20
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值