0

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;
}
4

1 に答える 1

0

In Hibernate (and JPA) you don't work primarily with IDs but with instances of objects. So instead of setting the ID of the parent, you need to load an instance of ParentType and then set it into an instance of ChildType.

In JPA (I'm more used to JPA) it would be something like:

long parentId = ...; // you get this from the sender system
ParentType parent =
    entityManager.find(ParentType.class, parentId);
// Now you can set the parent to instances of ChildType,
// and Hibernate will store the correct ID into the database.

In Hibernate it would be something like

...
ParentType parent =
    (ParentType)session.get(ParentType.class, parentId);
...
于 2012-08-08T18:23:18.563 に答える