0

FK によって関連付けられた 2 つのテーブルがあります。

テーブルの学生は次のようにマッピングされます。

@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'.

nullFK にも値を挿入する可能性はありますか?

私はそれを定義しましょうか:

  • エンティティレベルまたは
  • データベースレベル?

アップデート:

を変更しました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同じ列に 2 つの異なるフィールドをマップしました。

private School school;
private Integer school_ID; 

school_ID フィールドを削除します。School エンティティへの関連付けが既にあるため、これは必要ありません。

insertable = false, updatable = falseまた、関連マッピングからも削除します。このschoolフィールドを使用して、関連付けを作成、更新、または削除する必要があります。

于 2012-06-14T11:03:35.860 に答える