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一無所知。 –