当前位置: 欣欣网 > 码农

还在 MySQL 中使用枚举?小心有坑~

2024-04-19码农

为什么使用枚举

限定值的取值范围,比如性别(男,女,未知)等。

枚举类型使用陷阱

1.超级不推荐在mysql中设置某一字段类型为enum,但是存的值为数字,比如‘0’,‘1’,‘2’;

  • 解释1: 你会混淆,因为enum可以通过角标取值,但它的角标是从1开始,对于不熟悉这个字段的人这里会出错

  • 解释2: enum类型的字段对于0与‘0’有非常大的区别,如果你是用0当角标做操作,因它没有这个角标,所要会报错;如果你使用‘0’这个值去取枚举值,并做插入操作,你会发现它竟然会成功,但是插入的结果是一个「空」(不是null)

  • 解释3: enum类型对于php等弱语言类型的支持很差,弱语言类型打引号和不打引号的值可能是同一类型,但是对于mysql中enum类型的字段来说,那就不一定是一回事了

  • 结论:总之,不要拿mysql的enum类型取存一些数字;如果你一定要使用这个字段去存数字,请把这个字段定义为int,然后在java代码中使用枚举类做一个对于这个字段值范围的一个限定!(后面有代码)

    2.你可能会报这个错—— Caused by: java.sql.SQLException: Data truncated for column 'Color' at row 1 ;

    原因:

  • Jpa默认使用整数顺序值持久化枚举类型;

  • Mysql中枚举类型Color定义取值的顺序是 RED、GREEN、BLUE ,因此,当这三个取值持久化到数据库表时,取值分别是0、1、2;

  • 意思就是我们这里存往数据库的数据是0、1、2这样的数字,而不是 RED、GREEN、BLUE 字符串,但是Mysql数据库中定义的是 RED、GREEN、BLUE ,并没有其它值所以报错

  • 解决:在entity中使用 @Enumerated(EnumType.STRING) 标注你的枚举类型属性,如果标注,默认是integer

    使用例子

    建表语句为

    CREATETABLE test4 (
    idBIGINTUNSIGNED PRIMARY KEY AUTO_INCREMENT,
    brand VARCHAR(255NOTNULL,
    color ENUM('RED','GREEN','BLUE')
    ENGINE = InnoDB

    Java代码中,枚举类

    publicenum Color {
    RED,
    GREEN,
    BLUE
    }

    Java代码中,Javabean

    @Entity
    @Table(name="test4"
    public classClothesRight{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Enumerated(EnumType.STRING)
    private Color color;
    private String brand;
    public Long getId(){
    return id;
     }
    publicvoidsetId(Long id){
    this.id = id;
     }
    public String getBrand(){
    return brand;
     }
    publicvoidsetBrand(String brand){
    this.brand = brand;
     }
    publicClothesRight(Long id, Color color, String brand){
    super();
    this.id = id;
    this.color = color;
    this.brand = brand;
     }
    public Color getColor(){
    return color;
     }
    publicvoidsetColor(Color color){
    this.color = color;
     }
    publicClothesRight(){
    super();
     }
    }









    简单使用:

    publicinterfaceTest4RightRepositoryextendsJpaRepository<ClothesRightLong>{
    }
    @Autowired
    private Test4RightRepository t4R;
    /**
    * 使用@Enumrated()标注字段为枚举的数据
    * 结果 正确插入RED
    */

    @GetMapping(value="/addclothesright")
    publicvoidGetTest4Right(){
    List<ClothesRight> entities = new ArrayList<>();
    ClothesRight clothes = new ClothesRight();
    //clothes.setId(1L);
    clothes.setBrand("佐丹奴");
    clothes.setColor(Color.RED); 
    entities.add(clothes);
    t4R.save(entities);
     }

    结果为:

    插入数字例子(不推荐)

    建表

    CREATETABLE test5num (
    idBIGINTUNSIGNED PRIMARY KEY AUTO_INCREMENT,
    used int(11DEFAULTNULLCOMMENT'0:没用过 1:已用过 2:不能用'
     )ENGINE = InnoDB

    Java代码为:

    @Entity
    @Table(name="test5num")
    public classTest5Num{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private Used used;
    public Long getId(){
    return id;
     }
    publicvoidsetId(Long id){
    this.id = id;
     }
    public Used getUsed(){
    return used;
     }
    publicvoidsetUsed(Used used){
    this.used = used;
     }
    publicTest5Num(){
    super();
     }
    publicTest5Num(Long id, Used used){
    super();
    this.id = id;
    this.used = used;
     }
    }
    /**
    *枚举类
    */

    publicenum Used {
     UNUSED(0,"没用过"),
     USED(1,"已用过"),
     FORBIDDEN(2,"不能用");
    private Integer code;
    private String discribe;
    public Integer getCode(){
    return code;
     }
    public String getDiscribe(){
    return discribe;
     }
    privateUsed(Integer code, String discribe){
    this.code = code;
    this.discribe = discribe;
     }
    }
    /**
     * dao层
     */

    publicinterfaceTest5NumRepositoryextendsJpaRepository<Test5NumLong>{
    }
    @Autowired
    private Test5NumRepository t5N;
    /**
     * mysql枚举的字段类型不宜插入数字,但是需求就是要用数字,怎么办?
     * 解决:mysql数据类型定义为int,枚举限定在java代码中解决
     * 
     */

    @GetMapping("/test5insert")
    publicvoidinsertT5(){
     Test5Num t5 = new Test5Num();
     t5.setUsed(Used.USED);
     List<Test5Num> list = new ArrayList<Test5Num>();
     list.add(t5);
     t5N.save(list);
    }








    结果:

    来源:blog.csdn.net/u011442682/

    article/details/79078199

    >>

    END

    精品资料,超赞福利,免费领

    微信扫码/长按识别 添加【技术交流群

    群内每天分享精品学习资料

    最近开发整理了一个用于速刷面试题的小程序;其中收录了上千道常见面试题及答案(包含基础并发JVMMySQLRedisSpringSpringMVCSpringBootSpringCloud消息队列等多个类型),欢迎您的使用。

    👇👇

    👇点击"阅读原文",获取更多资料(持续更新中