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

 

 

原网站

版权声明
本文为[Fat technology house]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207221901550810.html