Hibernate を使用して親子オブジェクトを永続化しています。ここで、親にはid
、送信側システムからの主キーであり、常に一意である が付属しています。
親 ID を持つすべての新しい受信オブジェクトが存在しない場合、親オブジェクトはアプリケーション データベース固有の主キーと共に親テーブルに挿入されParentPK
、子行は対応する で挿入されParentFK
ます。
親 ID がアプリケーション データベースに既に存在する場合は、親テーブルのみを更新する必要があります。しかし、ParentPK が既に存在する場合、子行に ParentFK を挿入するにはどうすればよいですか? テーブル構造:
CREATE TABLE Parent(
ParentPK bigint NOT NULL,
TypeCode int NULL,
Id bigint NULL,
FullName varchar(50) NULL
}
CREATE TABLE Child(
ChildPK bigint NOT NULL,
Code int NULL,
Designation int NULL,
ParentFK bigint NULL
}
ALTER TABLE Child ADD
CONSTRAINT FK_Child_Parent FOREIGN KEY(ParentFK)
REFERENCES Parent (ParentPK)
エンティティ クラス:
@Entity
@Table(name="Parent")
public class ParentType extends HibernateEntity{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="KeyGenerator")
@GenericGenerator(name = "KeyGenerator",
strategy = "services.db.hibernate.KeyGenerator")
protected Long parentPK;
protected String id;
protected int typeCode;
protected String fullName;
@OneToMany(mappedBy="parent",targetEntity=ChildType.class,fetch=FetchType.LAZY,cascade = CascadeType.ALL)
protected List<ChildType> child;
}
@Entity
@Table(name="Child")
public class ChildType extends HibernateEntity{
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="KeyGenerator")
@GenericGenerator(name = "KeyGenerator",
strategy = "services.db.hibernate.KeyGenerator")
protected Long childPK;
protected int code;
protected int designation;
@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="ParentFK")
protected ParentType parent;
}