当前位置:网站首页>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 :

边栏推荐
- In the name of "upgrade", talk about the core technology of cloud native data warehouse analyticdb
- Alibaba cloud disk IOS / Android version 3.8.0 update, video can be cached according to the definition
- 听书项目开发过程及重难点总结
- 网站禁用f12 禁止调试代码方法
- Linux环境下oracle切换用户并查询数据库命令
- Test how to use Fiddler to connect the mobile packet capturing app
- OWA邮件系统登录双因子认证(短信认证)方案
- [JS] ES6 let, const define variables
- BGP的选路原则
- How about opening an account of Huatai Securities ETF fund? Is it safe
猜你喜欢

引擎提示Alias HeroDB跟游戏引擎启动异常怎么解决?

众昂矿业:萤石色彩丰富,极具审美价值

第三章 Encog Workbench

第一章 回归,分类 & 聚类

YOLOv7——论文简述

OWA email system login two factor authentication (SMS authentication) scheme
![swing-[MyNote]-实现像IDEA一样的定位scroll from souce功能](/img/ee/53aae922d7a4b3df3871a3e997cc57.png)
swing-[MyNote]-实现像IDEA一样的定位scroll from souce功能

以“升舱”之名,谈谈云原生数据仓库 AnalyticDB 的核心技术

ZLMediaKit尝试解决GB28181(UDP方式)的视频花屏问题

【机器学习】模型选择(性能度量)原理及实战
随机推荐
Idea debug is stuck during startup. Solution
Web3产品经理指南:如何面向加密世界
2022备忘录
JS Boolean undefined null typeof type conversion number() parseint() parsefloat string tostring() calculator
MySq 数据库约束
强化学习2
Alibaba cloud disk IOS / Android version 3.8.0 update, video can be cached according to the definition
ZLMediaKit尝试解决GB28181(UDP方式)的视频花屏问题
Day27 operation
引擎提示Alias HeroDB跟游戏引擎启动异常怎么解决?
阿里云盘 iOS /安卓版 3.8.0 更新,可根据清晰度缓存视频了
Summer vacation notes 1
Basic concepts of relational database
常用正则表达式最强整理速查手册(荣耀典藏版)
第一章 回归,分类 & 聚类
R语言箱线图添加 t.test 显著性-
【JS】ES6-let、const定义变量
Zhongang Mining: fluorite is rich in color and has great aesthetic value
Chapter VIII using time series data
R language drawing oblique diagram