Java枚舉自動轉(zhuǎn)換存入MySQL

首發(fā)于:http://www.meibug.net/service/105.html

框架SpringBoot MyBatis TypeHandler

主要使用mybatis中的TypeHandler接口

在java中使用如下枚舉:

public enum Status {
    DELETED(-1, "已刪除"),
    NORMAL(1, "正常");
    
    private final int code;
    private final String text;
    
    public int code() {
        return code;
    }

    public String text() {
        return text;
    }

}

java中的entity:

public class DemoEntity{
    private Long id;
    private String name;
    private Integer status;
}

如果我在java中使用枚舉不用處理的情況下,存入到數(shù)據(jù)之前需要手動使用Status.code()獲取到枚舉的code,然后放入entity,才能獲取通過mybatis存入數(shù)據(jù)庫
如果我想在DemoEntity 中直接使用Status枚舉,而且mybaits還能夠正常存入,這個時候就需要用的TypeHandler

mybaits的相關(guān)資料:
http://www.mybatis.org/mybatis-3/zh/configuration.html#typeHandlers

首先把entity修改為:

public class DemoEntity{
    private Long id;
    private String name;
    private Status status;
}

然后創(chuàng)建一個handler實現(xiàn)TypeHandler接口,注意類上方的注解

@MappedTypes(value = Status.class) 這個一定要加

@MappedTypes(value = Status.class)
public class StatusHandler implements TypeHandler<Status> {

    @Override
    public Status getResult(ResultSet rs, String column) throws SQLException {
        return Status.codeOf(rs.getInt(column));
    }

    @Override
    public Status getResult(ResultSet rs, int i) throws SQLException {
        return Status.codeOf(rs.getInt(i));
    }

    @Override
    public Status getResult(CallableStatement cs, int i) throws SQLException {
        return Status.codeOf(cs.getInt(i));
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, Status param, JdbcType jdbcType) throws SQLException {
        ps.setByte(i, (byte)param.code());
    }

}

因為我使用的是SpringBoot 所有我在springboot 中的properties文件中添加mybatis.type-handlers-package屬性

mybatis.type-handlers-package=你的handler所在的包

測試一下:插入和查找都OK

參考文章:
https://blog.csdn.net/u014044812/article/details/78258730?ticket=ST-37407-ue2hxKqa95tBi6Xdoayo-passport.csdn.net

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容