为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 68 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信