【问题标题】:Hibernate: Set Foreign key to new Child Table row which is referencing existing Parent PK休眠:将外键设置为引用现有父 PK 的新子表行
【发布时间】:2012-08-09 02:23:18
【问题描述】:

我正在使用 Hibernate 持久化一个父子对象。这里的 Parent 带有一个 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;
}

【问题讨论】:

  • 我认为信息太少无法提供帮助。你能发布你的数据库表的样子或你的实体类吗?
  • @PetrPudlák 更新了表和实体类信息。

标签: java hibernate orm


【解决方案1】:

在 Hibernate(和 JPA)中,您主要使用的不是 ID,而是对象实例。所以不用设置父ID,你需要加载ParentType的实例,然后设置成ChildType的实例。

在 JPA 中(我更习惯 JPA)它会是这样的:

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.

在 Hibernate 中是这样的

...
ParentType parent =
    (ParentType)session.get(ParentType.class, parentId);
...

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2012-02-05
    • 1970-01-01
    • 2017-03-08
    相关资源
    最近更新 更多