当前位置:网站首页>Pay attention to the pitfalls of using enumeration in MySQL!
Pay attention to the pitfalls of using enumeration in MySQL!
2022-07-23 06:53:00 【Fat technology house】
Why use enumeration
Value range of limit value , Like gender ( male , Woman , Unknown ) etc. .
Enum types use traps
1. Super not recommended in mysql Set a field type to enum, But the stored value is a number , such as ‘0’,‘1’,‘2’;
explain 1: You will confuse , because enum You can take values through angle marks , But its angle sign is from 1 Start , For those who are not familiar with this field, there will be an error
explain 2: enum Fields of type are for 0 And ‘0’ There's a big difference , If you use 0 When the angle mark does the operation , Because it doesn't have this angle sign , What you want will report an error ; If you use ‘0’ This value is used to get the enumeration value , And insert it , You will find that it will succeed , But the result of the insertion is a “ empty ”( No null)
explain 3: enum Type for php And other weak language types are poorly supported , The quoted and unquoted values of weak language types may be of the same type , But for mysql in enum For fields of type , That's not necessarily the same thing
Conclusion : All in all , Don't take it. mysql Of enum Type take and save some numbers ; If you have to use this field to save numbers , Please define this field as int, And then in java The code uses the enumeration class to limit the value range of this field !( There's code behind it )
2. You may report this error ——Caused by: java.sql.SQLException: Data truncated for column 'Color' at row 1 ;
reason :
Jpa By default, integer sequential values are used to persist enumeration types ;
Mysql Enumeration types in Color The order in which values are defined is
RED、GREEN、BLUE, therefore , When these three values are persisted to the database table , The values are 0、1、2;This means that the data stored in the database here is 0、1、2 Numbers like this , instead of
RED、GREEN、BLUEcharacter string , however Mysql What is defined in the database isRED、GREEN、BLUE, There is no other value, so an error is reported
solve : stay entity Use in
@Enumerated(EnumType.STRING)Label your enum type properties , If marked , The default is integer
Examples of use
The predicative sentence is
CREATE TABLE test4 (
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
brand VARCHAR(255) NOT NULL,
color ENUM('RED','GREEN','BLUE')
) ENGINE = InnoDB;
Java In the code , Enumeration class
public enum Color {
RED,
GREEN,
BLUE
}
Java In the code ,Javabean
@Entity
@Table(name="test4")
public class ClothesRight {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private Color color;
private String brand;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public ClothesRight(Long id, Color color, String brand) {
super();
this.id = id;
this.color = color;
this.brand = brand;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public ClothesRight() {
super();
}
}
Easy to use :
public interface Test4RightRepository extends JpaRepository<ClothesRight, Long>{
}
@Autowired
private Test4RightRepository t4R;
/**
* Use @Enumrated() Label fields as enumerated data
* result Insert... Correctly RED
*/
@GetMapping(value="/addclothesright")
public void GetTest4Right(){
List<ClothesRight> entities = new ArrayList<>();
ClothesRight clothes = new ClothesRight();
//clothes.setId(1L);
clothes.setBrand(" Giordano ");
clothes.setColor(Color.RED);
entities.add(clothes);
t4R.save(entities);
}
The result is :

Insert a numerical example ( Not recommended )
Build table
CREATE TABLE test5num (
id BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
used int(11) DEFAULT NULL COMMENT '0: Never used 1: Used 2: Out-of-service '
)ENGINE = InnoDB;
Java The code is :
@Entity
@Table(name="test5num")
public class Test5Num {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private Used used;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Used getUsed() {
return used;
}
public void setUsed(Used used) {
this.used = used;
}
public Test5Num() {
super();
}
public Test5Num(Long id, Used used) {
super();
this.id = id;
this.used = used;
}
}
/**
* Enumeration class
*/
public enum Used {
UNUSED(0," Never used "),
USED(1," Used "),
FORBIDDEN(2," Out-of-service ");
private Integer code;
private String discribe;
public Integer getCode() {
return code;
}
public String getDiscribe() {
return discribe;
}
private Used(Integer code, String discribe) {
this.code = code;
this.discribe = discribe;
}
}
/**
* dao layer
*/
public interface Test5NumRepository extends JpaRepository<Test5Num, Long>{
}
@Autowired
private Test5NumRepository t5N;
/**
* mysql Enumerating field types should not be inserted with numbers , But needs are numbers , What do I do ?
* solve :mysql The data type is defined as int, Enumeration is limited to java Solve in code
*
*/
@GetMapping("/test5insert")
public void insertT5(){
Test5Num t5 = new Test5Num();
t5.setUsed(Used.USED);
List<Test5Num> list = new ArrayList<Test5Num>();
list.add(t5);
t5N.save(list);
}
result :

边栏推荐
猜你喜欢

OWA email system login two factor authentication (SMS authentication) scheme

HMS Core Discovery第16期直播预告|与虎墩一起,玩转AI新“声”态

JS complex data type

Gom引擎Key.lic配套的X-FKGOM授权启动

LSA related content in OSPF

Sharepreference principle + practical analysis

Thread类中run和start的区别

第七章 其他神经网络类型
![传奇私服GOM引擎启动M2提示:[X-FKGOM] 已经加载成功卡住的怎么处理?](/img/32/df602f294e009c9462d955b1819ffe.png)
传奇私服GOM引擎启动M2提示:[X-FKGOM] 已经加载成功卡住的怎么处理?

1. Summary of strengthening learning foundation
随机推荐
技术团队:提升团队效能,从不做3件事开始
Illustration and text demonstrate the movable range of the applet movable view
测试必会的如何利用fiddler连接手机抓包APP
IO流原理及流的分类
Jmeter-记一次自动化造数引发的BeanShell写入excel实例
Day27 operation
反射(类的加载)
支持SwiftUI!Swift版图片&视频浏览器-JFHeroBrowser上线啦
第九章 使用图像数据
JS 复杂数据类型
强化学习2
How to package your project and let other users install it through pip
以“升舱”之名,谈谈云原生数据仓库 AnalyticDB 的核心技术
面试官:大量请求 Redis 不存在的数据,从而影响数据库,该如何解决?
JS complex data type
Test how to use Fiddler to connect the mobile packet capturing app
Can the generation whose middle-aged crisis comes ahead of time still live calmly?
Sharepreference principle + practical analysis
Codeforces Round #808 (Div. 2) C,D Codeforces Round #809 (Div. 2) C
数仓:流批一体的探索与实践