SpringBoot Entity中枚舉類型詳細使用介紹
簡介方案對比
本處列舉表示類型或狀態(tài)的常用方法的對比。
法1:使用數(shù)字表示(不推薦)
//1:支付寶支付;2:微信支付;3:銀行卡支付 private Integer payType;
這種方法的缺點:可讀性極差,排查問題也麻煩。比如:前端頁面上看到了2這個類型,還要看接口文檔或者問后端這是什么意思,浪費時間!
法2:使用字符串表示(不推薦)
//ALIPAY:支付寶;WECHAT_PAY:微信;BANK_CARD_PAY:銀行卡支付 private String payType;
這種方式比法1好一些了,提高了數(shù)據(jù)庫的可讀性和排查問題速度。
缺點:難以控制不允許數(shù)據(jù)庫的pay_type為空字符串這種情況;支持的類型沒有限制死,前端傳個其他的字符串也能存入數(shù)據(jù)庫。
法3:使用枚舉表示(推薦)
枚舉是這種場景最好的方案(枚舉本身就是為了表示可窮舉類型而發(fā)明出來的!)。
定義一個枚舉類
package com.example.demo.order.enums;
import lombok.Getter;
@Getter
public enum PayTypeEnum {
ALIPAY("支付寶"),
WECHAT_PAY("微信支付"),
BANK_CARD_PAY("銀行卡支付"),
;
private final String description;
PayTypeEnum(String description) {
this.description = description;
}
}Entity中定義枚舉類型字段
private PayTypeEnum payType;
優(yōu)點
- 可讀性極高,排查問題很快(比如:前端頁面上看到ALIPAY這個類型,一眼就能知道是支付寶)
- 可以控制不允許數(shù)據(jù)庫的pay_type為空字符串這種情況(因為枚舉字段不可能有空字符串)
- 支持的類型限制死,前端傳個其他的字符串無法存入數(shù)據(jù)庫。
枚舉用法示例
建表
CREATE TABLE `t_order` ( `id` bigint NOT NULL COMMENT 'ID', `order_no` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '訂單號', `pay_type` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '支付類型。ALIPAY:支付寶;WECHAT_PAY:微信;BANK_CARD_PAY:銀行卡支付。', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='訂單';
pay_type字段加了NOT NULL限制。
Entity
package com.example.demo.order.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.example.demo.order.enums.PayTypeEnum;
import lombok.Data;
@Data
@TableName("t_order")
public class Order {
private Long id;
private String orderNo;
private PayTypeEnum payType;
}Enum
package com.example.demo.order.enums;
import lombok.Getter;
@Getter
public enum PayTypeEnum {
ALIPAY("支付寶"),
WECHAT_PAY("微信支付"),
BANK_CARD_PAY("銀行卡支付"),
;
private final String description;
PayTypeEnum(String description) {
this.description = description;
}
}Controller
package com.example.demo.order.controller;
import com.example.demo.order.entity.Order;
import com.example.demo.order.service.OrderService;
import com.example.demo.user.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private OrderService orderService;
@PostMapping("pay")
public void pay(@RequestBody Order order) {
orderService.save(order);
}
}Service
接口
package com.example.demo.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.demo.order.entity.Order;
public interface OrderService extends IService<Order> {
}實現(xiàn)
package com.example.demo.order.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.order.entity.Order;
import com.example.demo.order.mapper.OrderMapper;
import com.example.demo.order.service.OrderService;
import org.springframework.stereotype.Service;
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
}Mapper
package com.example.demo.order.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.order.entity.Order;
import org.springframework.stereotype.Repository;
@Repository
public interface OrderMapper extends BaseMapper<Order> {
}測試
1.正常操作
寫入成功,枚舉的name()方法的值會寫到數(shù)據(jù)庫。

后端結果

數(shù)據(jù)庫結果

2.前端傳空字符串
此時會報錯,因為枚舉中沒有對應空字符串的。

后端結果(無法將空字符串反序列化為枚舉對象)
2022-09-10 10:14:30.406 WARN 128760 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `com.example.demo.order.enums.PayTypeEnum` from String "": not one of the values accepted for Enum class: [ALIPAY, BANK_CARD_PAY, WECHAT_PAY]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.example.demo.order.enums.PayTypeEnum` from String "": not one of the values accepted for Enum class: [ALIPAY, BANK_CARD_PAY, WECHAT_PAY]
at [Source: (PushbackInputStream); line: 4, column: 16] (through reference chain: com.example.demo.order.entity.Order["payType"])]
數(shù)據(jù)庫結果(沒寫入數(shù)據(jù))

3.前端傳null

后端結果(pay_type為null,寫入數(shù)據(jù)庫時報錯)
2022-09-10 10:24:20.514 ERROR 128760 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException:
### Error updating database. Cause: java.sql.SQLException: Field 'pay_type' doesn't have a default value
### The error may exist in com/example/demo/order/mapper/OrderMapper.java (best guess)
### The error may involve com.example.demo.order.mapper.OrderMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO t_order ( id, order_no ) VALUES ( ?, ? )
### Cause: java.sql.SQLException: Field 'pay_type' doesn't have a default value
; Field 'pay_type' doesn't have a default value; nested exception is java.sql.SQLException: Field 'pay_type' doesn't have a default value] with root cause
java.sql.SQLException: Field 'pay_type' doesn't have a default value
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.25.jar:8.0.25]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.25.jar:8.0.25]
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.25.jar:8.0.25]
at com.mysql.cj.jdbc.ClientPreparedStatement.execute(ClientPreparedStatement.java:370) ~[mysql-connector-java-8.0.25.jar:8.0.25]
at com.zaxxer.hikari.pool.ProxyPreparedStatement.execute(ProxyPreparedStatement.java:44) ~[HikariCP-3.4.5.jar:na]
......
數(shù)據(jù)庫結果(沒寫入數(shù)據(jù))

到此這篇關于SpringBoot Entity中枚舉類型詳細使用介紹的文章就介紹到這了,更多相關SpringBoot Entity內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用mongoTemplate實現(xiàn)多條件加分組查詢方式
這篇文章主要介紹了使用mongoTemplate實現(xiàn)多條件加分組查詢方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-06-06
RedisKey的失效監(jiān)聽器KeyExpirationEventMessageListener問題
這篇文章主要介紹了RedisKey的失效監(jiān)聽器KeyExpirationEventMessageListener問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

