Mybatis-plus: springboot 2.1.4 引入mybatis-plus 3.1.0 使用枚举类型,往数据库写入的是code,查询时该枚举类型没有值

Created on 18 Apr 2019  ·  12Comments  ·  Source: baomidou/mybatis-plus

mybatis plus 3.1.0

user中的genderEnum枚举类insert的时候显示正常,但是在查询的时候,没genderEnum无法获取到数据库字段映射的值。

重现步骤

user.java
`@TableId(value = "id", type = IdType.NONE)
private Long id;

private String mobile;
private String encodedPassword;
private String name;
private String nickName;
private String headIcon;
@TableField(value = "gender", el = "gender, jdbcType=BIGINT")
private GenderEnum gender;`

GenderEnum.java
`public enum GenderEnum implements IEnum {

/**
 * male
 */
MALE(1, "女"),

/**
 * female
 */
FEMALE(2, "男");

private int code;
private String descritpion;

GenderEnum(int code, String descritpion) {
    this.code = code;
    this.descritpion = descritpion;
}

public void setCode(int code) {
    this.code = code;
}

public int getCode() {
    return code;
}

@JsonValue
public String getDescritpion() {
    return descritpion;
}

public void setDescritpion(String descritpion) {
    this.descritpion = descritpion;
}

@Override
public Integer getValue() {
    return this.code;
}

}`

configuration:
map-underscore-to-camel-case: true
default-enum-type-handler: com.baomidou.mybatisplus.extension.handlers.EnumTypeHandler

userMapper.java
public interface UserMapper extends BaseMapper<User> { }

报错信息

查询时,gender没有值。

Most helpful comment

看下数据库字段类型是什么,如果是tinint(1)的话会有问题

All 12 comments

把你配置的default-enum-type-handler删掉试试

删掉不行的,还是没有查询出来

User(mobile=17816853545, encodedPassword=12345678, name=春晓sir, nickName=virgil, headIcon=http://f.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3ce863f8b519c45d688d53f20d0.jpg, **** gender=null ****, deleted=0)
INSERT INTOcnasir_driver.user(id,mobile,encoded_password,name,nick_name,head_icon,gender,deleted,created_date,last_modified_date,version) VALUES (22, '17816853545', '12345678', '春晓sir', 'virgil', 'http://f.hiphotos.baidu.com/image/pic/item/4610b912c8fcc3ce863f8b519c45d688d53f20d0.jpg', **** '2' ****, 0, '2019-04-19 11:33:02', '2019-04-19 11:33:02', 1);

去除你的 jdbcType=BIGINT试试.

你好,大佬 ~
我把jdbcType去掉了还是不行
我把代码push到github了,大佬有空的帮我看看
https://github.com/pleasecallmeleifeng/cnasir-driver

看下数据库字段类型是什么,如果是tinint(1)的话会有问题

看下数据库字段类型是什么,如果是tinint(1)的话会有问题
提醒到了,应该是这问题.

我把数据库的gender字段类型写成了varchar, 导致了读取没有匹配到GenderEnum, 谢谢大佬的解答。

结论:枚举类型所对应的数据库字段必须设置为int。

implements IEnum:

@Override
public Integer getValue() {
return this.code;
}

这里是指定数据库用到字段值,这里是integer,数据库当然得匹配用int

我也是改成tinint(1)就出问题了~~ 哈哈 大佬能解释一下么 科普科普

插入的时候从0开始的,怎么根据enum的code插入到数据库呢?

@TableField(value = "gender")
private GenderEnum gender;

参考枚举使用sample:

https://gitee.com/baomidou/mybatis-plus-samples/tree/master/mybatis-plus-sample-enum

Was this page helpful?
0 / 5 - 0 ratings