当前位置:网站首页>Still using enumeration in MySQL? Pay attention to these traps!
Still using enumeration in MySQL? Pay attention to these traps!
2022-07-16 07:48:00 【Dream, wake up】
Why use enumeration
Value range of limit value , Like gender ( male , Woman , Unknown ) etc. .
Enum types use traps
One 、 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 )
Two 、 You may report this error ——Caused by: java.sql.SQLException: Data truncated forcolumn ‘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、BLUE character string , however Mysql What is defined in the database is RED、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 :

Code machine records code life ................
边栏推荐
- LVM与磁盘配额
- Redis只能做缓存?太out了!
- "Finally I left bytek..." confession of a test engineer with an annual salary of 40W
- 求职3个月,简历大多都石沉大海,一说是手工测试都连连摇头~太难了
- 自动备份MySQL。且保留7天案例
- Transport layer protocol
- On the meaning of XML file format in the framework
- Is it true that you can't do software testing until you're 35? So what should I do I'm 36
- 还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS
- 【LeetCode】796. Rotate string
猜你喜欢

Desired in appium_ Caps parameter record

字典树

Obtaining control coordinates and control properties in appium

How to write test cases for initial testing? Take you to write a qualified test case from three aspects

socket详解

TCP协议详解

Redis主从集群搭建及哨兵模式配置

Redis master-slave cluster construction and sentinel mode configuration

还在使用 MySQL 中使用枚举?这些陷阱一定要注意!

JVM object creation and memory allocation mechanism
随机推荐
丑数
将一个数分解成多个加数相加的形式
还在用策略模式解决 if-else?Map+函数式接口方法才是YYDS
线程池和生产者消费者模型
Is it true that you can't do software testing until you're 35? So what should I do I'm 36
Select / poll / epoll explanation
Five years' experience: the monthly salary is 3000 to 30000, and the change of Test Engineers
Seckill activity development
2-3 tree B tree b+ tree
接口测试与接口测试自动化
jmeter中设置登录接口只调用一次
【LeetCode】796. Rotate string
druid数据库连接池监控页面
It is said that the salary of software testing is high, so how can the monthly salary of software testing exceed 10K
socket详解
As an interviewer for the test development post, how do I choose people?
How to solve the relationship between the two use cases?
Redis只能做缓存?太out了!
Linux下安装单机版redis
Automatically back up mysql. And keep the case for 7 days