问题描述
我有两个类,一个包含在另一个类中。学校班级和学生
在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设置。