我有两张由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'.
我是否有可能在FK上插入null
值?
我要定义它:
更新:
我已更改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
view.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>
答案 0 :(得分:1)
您在同一school_id
列上映射了两个不同的字段:
private School school;
private Integer school_ID;
删除school_ID字段。您不需要它,因为您已经与学校实体建立了关联。
并从关联映射中删除insertable = false, updatable = false
。您应该使用school
字段来创建,更新或删除关联。