Hibernate 5.3.10一对多insertable = false的行为与Hibernate 5.2.1不同

问题描述

我有两个类,一个包含在另一个类中。学校班级和学生 在Hibernate 5.2.1中持久保存它们时,一切都按预期方式工作,但是在Hibernate 5.3.10中持久保存时,我必须删除或设置insertable = true才能获得相同的结果,否则会出现异常。

我要寻找的是确认休眠行为已更改的确认。何时何地,为什么...

我根本找不到任何与此相关的文档。

jdbc.spi.SqlExceptionHelper - NULL not allowed for column "schoolClassId"; SQL statement:
insert into tStudent (studentId,name) values (null,?)
org.hibernate.exception.ConstraintViolationException: could not execute statement
javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement.
@Entity
@Table(name = "tSchoolClass")
@AutowiringTarget
public class SchoolClass {

   
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "schoolClassId")
    private Long id;


    @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
    @JoinColumn(name = "schoolClassId",nullable = false,insertable = false,updatable = false)
    private List<Student> students;
@Entity
@Table(name = "tStudents")
@AutowiringTarget
public class Students {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "StudentId")
    private Long id;

H2数据库。

CREATE TABLE tSchoolClass (
    schoolClassId int IDENTITY(1,1) NOT NULL,CONSTRAINT PK_tSchoolClass PRIMARY KEY (schoolClassnId));

CREATE TABLE tStudents (
    studentId  int IDENTITY(1,schoolClassint NOT NULL,CONSTRAINT PK_tStudents PRIMARY KEY (studentId),CONSTRAINT FK_tStudent_tSchoolClass FOREIGN KEY (schoolClassId) REFERENCES tSchoolCLass (SchoolClassId));

解决方法

NULL not allowed for column "schoolClassId"异常清楚地表明schoolClassId不能为空。

它的nullable = false属性将对schoolClassId列实施非null约束,该列可以转换为学生创建表中的schoolClassId bigint NOT NULL

insertable=true列上的schoolClassId表示该列包含在插入查询中。因此,无论何时持久保存SchoolClass实例,关联的Student实例也将持久保存。学生实体插入将包括SchoolClassId列,该列的值引用SchoolClass id的实例,在这种情况下,该值不能为null。

因此,简而言之,每当schoolClassId列为null时,都会引发约束违例,因此保持insertable = false,如果必须消除违规,则需要将nullable = true设置。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...