MyBatis-Plus如何解決主鍵自增問題
MyBatis-Plus主鍵自增失敗
1、先看錯誤
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5c731754]
2022-12-05 21:05:55.322 ERROR 17476 --- [nio-8989-exec-1] 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: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'id' at row 1
### The error may exist in com/baidu/mapper/SysAccountMapper.java (best guess)
### The error may involve com.baidu.mapper.SysAccountMapper.insert-Inline
### The error occurred while setting parameters
### SQL: INSERT INTO account ( id, datatime ) VALUES ( ?, ? )
### Cause: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'id' at row 1
; Data truncation: Out of range value for column 'id' at row 1; nested exception is com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'id' at row 1] with root causecom.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Out of range value for column 'id' at row 1
大概意思就是說,mybatis-plus添加數(shù)據(jù)的主鍵失敗。
2、需求
想要數(shù)據(jù)庫中添加數(shù)據(jù),成自增的。
我明明在數(shù)據(jù)庫設(shè)置了主鍵id自增,但是添加數(shù)據(jù)的時候沒有自增那。
3、解決
1、在數(shù)據(jù)庫中添加確保是自增。

2、在實體類上頁添加自增

4、自增策略
- 要想主鍵自增需要配置如下主鍵策略
- 需要在創(chuàng)建數(shù)據(jù)表的時候設(shè)置主鍵自增
- 實體字段中配置 @TableId(type = IdType.AUTO)
MyBatis-Plus插入后獲取自增主鍵
1、在主鍵上的**@TableId注解增加屬性 type**。

2、設(shè)置之后,在調(diào)用mapper.insert(domain)方法之后,插入完成后,直接能從domain中取到最新的主鍵。

結(jié)果如下:

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Spring Cloud Feign作為HTTP客戶端調(diào)用遠程HTTP服務(wù)的方法(推薦)
在Spring Cloud中使用Feign, 我們可以做到使用HTTP請求遠程服務(wù)時能與調(diào)用本地方法一樣的編碼體驗,開發(fā)者完全感知不到這是遠程方法,更感知不到這是個HTTP請求,具體內(nèi)容詳情大家參考下本文2018-01-01
使用Java高效將CSV轉(zhuǎn)換為Excel的實現(xiàn)方法
在日常的數(shù)據(jù)處理和分析工作中,CSV文件因其輕量級和通用性而廣受歡迎,然而,當我們需要進行復(fù)雜的數(shù)據(jù)分析或利用Excel強大的圖表和公式功能時,將CSV數(shù)據(jù)轉(zhuǎn)換為Excel文件就成了開發(fā)者們常見的需求和痛點,本文將深入探討如何利用Java高效地將CSV轉(zhuǎn)換為Excel2025-08-08
GSON實現(xiàn)Java對象的JSON序列化與反序列化的實例教程
GSON是Google開發(fā)并開源的一個Java的JSON轉(zhuǎn)換庫,這里我們將來講解GSON實現(xiàn)Java對象的JSON序列化與反序列化的實例教程,需要的朋友可以參考下2016-06-06

