我有两个由 FK 关联的表。
表学生的映射如下:
@Entity
@Table(name="student")
public class Student implements Serializable {
...
@Id
@GeneratedValue
private int id;
@ManyToOne(fetch = FetchType.LAZY, optional = true)
@JoinColumn(name = "school_ID", nullable = true, insertable = false, updatable = false)
private School school;
private Integer school_ID;
@Transient
private boolean editable = false;
}
表学校:
@Entity
@Table(name="school")
public class School implements Serializable {
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "school")
private Set<Student> student = new HashSet<Student>(0);
当我尝试插入/更新不在任何学校(student.school_ID is null
)的学生时,它会报告:
Exception: java.lang.Exception: org.hibernate.exception.ConstraintViolationException:
could not update: [tables.Student#556758]
...
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The UPDATE statement
conflicted with the FOREIGN KEY constraint "FK__student__school_ID__57378E7F". The
conflict occurred in database "DB", table "dbo.school", column 'id'.
我是否有可能null
在 FK 上也插入值?
我应该定义它:
- 实体级别或
- 数据库级别?
更新:
我已经更改了private School school = new School()
,但是当我尝试插入/更新行时,它仍然报告:
SEVERE: Servlet.service() for servlet [Faces Servlet] in context with path [/DB] threw exception [javax.el.PropertyNotFoundException: /view.xhtml @183,102 value="#{item.school.id}": Target Unreachable, 'school' returned null] with root cause
javax.el.PropertyNotFoundException: /view.xhtml @183,102 value="#{item.school.id}": Target Unreachable, 'school' returned null
视图.xhtml:
<rich:column>
<h:outputText value="#{item.school != null ? item.school.name : null}" rendered="#{!item.editable}"/>
<h:selectOneMenu id="som" tabindex="1" value="#{item.school.id}" rendered="#{item.editable}">
<f:selectItems value="#{myDials.schoolList}"/>
</h:selectOneMenu>
</rich:column>
<rich:column>