SpringBoot Entity中枚舉類型詳細(xì)使用介紹
簡(jiǎn)介方案對(duì)比
本處列舉表示類型或狀態(tài)的常用方法的對(duì)比。
法1:使用數(shù)字表示(不推薦)
//1:支付寶支付;2:微信支付;3:銀行卡支付 private Integer payType;
這種方法的缺點(diǎn):可讀性極差,排查問(wèn)題也麻煩。比如:前端頁(yè)面上看到了2這個(gè)類型,還要看接口文檔或者問(wèn)后端這是什么意思,浪費(fèi)時(shí)間!
法2:使用字符串表示(不推薦)
//ALIPAY:支付寶;WECHAT_PAY:微信;BANK_CARD_PAY:銀行卡支付 private String payType;
這種方式比法1好一些了,提高了數(shù)據(jù)庫(kù)的可讀性和排查問(wèn)題速度。
缺點(diǎn):難以控制不允許數(shù)據(jù)庫(kù)的pay_type為空字符串這種情況;支持的類型沒(méi)有限制死,前端傳個(gè)其他的字符串也能存入數(shù)據(jù)庫(kù)。
法3:使用枚舉表示(推薦)
枚舉是這種場(chǎng)景最好的方案(枚舉本身就是為了表示可窮舉類型而發(fā)明出來(lái)的!)。
定義一個(gè)枚舉類
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)點(diǎn)
- 可讀性極高,排查問(wèn)題很快(比如:前端頁(yè)面上看到ALIPAY這個(gè)類型,一眼就能知道是支付寶)
- 可以控制不允許數(shù)據(jù)庫(kù)的pay_type為空字符串這種情況(因?yàn)槊杜e字段不可能有空字符串)
- 支持的類型限制死,前端傳個(gè)其他的字符串無(wú)法存入數(shù)據(jù)庫(kù)。
枚舉用法示例
建表
CREATE TABLE `t_order` ( `id` bigint NOT NULL COMMENT 'ID', `order_no` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '訂單號(hào)', `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> { }
實(shí)現(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> { }
測(cè)試
1.正常操作
寫入成功,枚舉的name()方法的值會(huì)寫到數(shù)據(jù)庫(kù)。
后端結(jié)果
數(shù)據(jù)庫(kù)結(jié)果
2.前端傳空字符串
此時(shí)會(huì)報(bào)錯(cuò),因?yàn)槊杜e中沒(méi)有對(duì)應(yīng)空字符串的。
后端結(jié)果(無(wú)法將空字符串反序列化為枚舉對(duì)象)
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ù)庫(kù)結(jié)果(沒(méi)寫入數(shù)據(jù))
3.前端傳null
后端結(jié)果(pay_type為null,寫入數(shù)據(jù)庫(kù)時(shí)報(bào)錯(cuò))
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ù)庫(kù)結(jié)果(沒(méi)寫入數(shù)據(jù))
到此這篇關(guān)于SpringBoot Entity中枚舉類型詳細(xì)使用介紹的文章就介紹到這了,更多相關(guān)SpringBoot Entity內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- spring boot 枚舉使用的坑整理
- spring boot mybatis枚舉映射示例代碼
- springboot枚舉類型傳遞的步驟
- SpringBoot實(shí)戰(zhàn)之高效使用枚舉參數(shù)(原理篇)案例詳解
- SpringBoot之使用枚舉參數(shù)案例詳解
- SpringBoot 枚舉類型的自動(dòng)轉(zhuǎn)換的實(shí)現(xiàn)
- springboot+mybatis+枚舉處理器的實(shí)現(xiàn)
- SpringBoot枚舉類型參數(shù)認(rèn)證的實(shí)現(xiàn)代碼
- SpringBoot自定義注解驗(yàn)證枚舉的實(shí)現(xiàn)
相關(guān)文章
SpringBoot項(xiàng)目部署到服務(wù)器上的方法(Jar包)
這篇文章主要介紹了SpringBoot項(xiàng)目部署到服務(wù)器上的方法(Jar包),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01Spring編程式和聲明式事務(wù)實(shí)例講解小結(jié)
這篇文章主要介紹了Spring編程式和聲明式事務(wù)實(shí)例講解小結(jié),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07使用mongoTemplate實(shí)現(xiàn)多條件加分組查詢方式
這篇文章主要介紹了使用mongoTemplate實(shí)現(xiàn)多條件加分組查詢方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06詳解JavaFX桌面應(yīng)用開發(fā)-Group(容器組)
這篇文章主要介紹了JavaFX桌面應(yīng)用開發(fā)-Group(容器組),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04RedisKey的失效監(jiān)聽器KeyExpirationEventMessageListener問(wèn)題
這篇文章主要介紹了RedisKey的失效監(jiān)聽器KeyExpirationEventMessageListener問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05