0
我有两个由FK关联的表。休眠 - 在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
值吗?
要不要我把它定义上:
- 实体级别或
- 数据库级别?
UPDATE:
我已经改变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>
再次感谢您。它似乎更好,但是当我尝试更新选定的项目时,它会报告nullPointerException(请参阅我的更新问题) – gaffcz
但是,实际上,表格学生只有'姓名','姓氏','年龄'和'school_id'列。没有行类型列... – gaffcz
更新与JSF相关,我对JSF一无所知。 –