I have two tables associated by FK.
Table student is mapped like this:
@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;
}
Table school:
@Entity
@Table(name="school")
public class School implements Serializable {
...
@OneToMany(fetch = FetchType.LAZY, mappedBy = "school")
private Set<Student> student = new HashSet<Student>(0);
When I try to insert/update student, which isn’t at any school (student.school_ID is null) it reports:
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'.
Do I have a possibility to insert also null values on FK?
Shall I define it on:
- entity level or
- database level?
UPDATE:
I’ve change the private School school = new School(), but when I try to insert/update row, it still reports:
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>
You mapped two different fields on the same
school_idcolumn:Remove the school_ID field. You don’t need it, since you already have an association to the School entity.
And also remove
insertable = false, updatable = falsefrom the association mapping. You should use theschoolfield to create, update or remove the association.