0

我有两个由 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>
4

1 回答 1

1

您在同一school_id列上映射了两个不同的字段:

private School school;
private Integer school_ID; 

删除 school_ID 字段。您不需要它,因为您已经与 School 实体建立了关联。

并且还insertable = false, updatable = false从关联映射中删除。您应该使用该school字段来创建、更新或删除关联。

于 2012-06-14T11:03:35.860 回答