亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JPA WrongArgumentException:SQL 字符串不能為 NULL:

JPA WrongArgumentException:SQL 字符串不能為 NULL:

holdtom 2023-10-19 21:39:25
我正在制作 Spring Boot (2.1.9) api,并使用 Postman 將一些 JSON POST 到我的控制器中的函數,該函數將其轉換為實體(作者)。我的控制器對象正確接收該對象及其字段,將其傳遞給我的服務對象并將其傳遞給我的數據訪問對象。調用 CrudRepository save(S實體) 函數時會出現問題,盡管打印了字段并驗證它們不為空,但我收到一個異常,聲稱我的字段確實為空。該實體未添加到數據庫中。我嘗試添加 auto_increment,更改生成類型。我嘗試過在 Postman 中發送 null 的 Id,也嘗試過不在 Postman 中發送 Id。我不知道如何解決這個問題,因為刪除 @GenerateValue 似乎可行,但并不理想,因為 save() 會根據這篇文章用新數據覆蓋具有相同 id 的任何預先存在的行。(注意:我還沒有完成任何正確的http狀態,我只想讓它在那之前工作)我的控制器:@RestController@RequestMapping(value = "/lms/admin*")public class AdminController{    @Autowired    AdminService admin;    @PostMapping(path = "/author", produces = "application/json", consumes="application/json")    public ResponseEntity<?> createAuthor(@RequestBody Author author)     {        return new ResponseEntity<>(admin.createAuthor(author),HttpStatus.OK);    }    /*other CRUD operations*/}我的服務:@Componentpublic class AdminService{    @Autowired    private AuthorDataAccess authorDao;    public Author createAuthor(Author author)    {        System.out.println(author.toString());        return authorDao.save(author);    }    /*other service functions*/}我的作者數據訪問@Componentpublic interface AuthorDataAccess extends CrudRepository<Author, Integer>{}我的作者實體:@Entity @Table(name = "tbl_author", schema = "library")public class Author implements Serializable{    private static final long serialVersionUID = 3002288345129007776L;    @Id    @GeneratedValue(strategy = GenerationType.SEQUENCE)    @Column(updatable = false)    private Integer authorId;    private String authorName;    public Author(){}    public Author(String authorName)    {        this.authorName = authorName;    }    public Author(Integer authorId, String authorName)    {        this.authorId = authorId;        this.authorName = authorName;    }    /*hashcode, equals, toString, getters, setters*/}mySQL 表:CREATE TABLE IF NOT EXISTS `library`.`tbl_author` (  `authorId` INT(11) NOT NULL,  `authorName` VARCHAR(45) NOT NULL,  PRIMARY KEY (`authorId`))ENGINE = InnoDBDEFAULT CHARACTER SET = latin1;
查看完整描述

1 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

在我開始創建 api 之前數據庫就已經存在

為了strategy = GenerationType.SEQUENCE工作,必須存在可用于列的數據庫序列authorId。另外,您需要使用@SequenceGenerator注釋指定其名稱,以便 JPA 知道如何找到它:

@GeneratedValue(generator = "authorIdGenerator", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "authorIdGenerator", sequenceName = <existing_sequence_name_in_the_db>, allocationSize=<correct_allocation_size_for_the_sequence>)

要獲取創建的實體的ID,需要再次遍歷表

為了獲取 ID,Hibernate 需要將更改刷新到 DB,因為是 DB 生成 ID。如果您使用JpaRepository代替作為CrudRepository基本接口,您將能夠調用saveAndFlush代替并讀取生成的ID。


查看完整回答
反對 回復 2023-10-19
  • 1 回答
  • 0 關注
  • 181 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號