如何在hibernate 3.6中级联保存简单的共享主键一对一映射

发布于 2024-10-01 12:20:13 字数 689 浏览 0 评论 0原文

我需要一个简单的休眠示例,其中一个实体与另一个实体具有一对一的关系,其中它们都共享主键。我只需要保存自动生成主键的主实体,其他依赖实体会自动级联保存。例如:

public class Person {
    @Id
    @GeneratedValue
    @Column(name = "Id")
    private Long id;

    @OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
    private Name name;
}

public class Name {
    @Id
    @Column(name = "Id")
    private Long id;

    @OneToOne
    @PrimaryKeyJoinColumn(name = "Id")
    private Person person;

    @Column
    private String first;
    @Column
    private String last;
}

Person person = new Person();
person.setName(new Name("first", "last"));
session.save(person);

我们能够轻松设置这两个实体。但我们要先保存人,然后通过hibernate保存名字。非常重要的是我们只需要救人。

I need a simple hibernate example of an entity with a one-to-one relationship with another entity where they both share the primary key. I need to only have to save the main entity that is auto-generating its primary key and the other dependent entity is cascade saved automatically. For example:

public class Person {
    @Id
    @GeneratedValue
    @Column(name = "Id")
    private Long id;

    @OneToOne(mappedBy = "person", cascade = CascadeType.ALL)
    private Name name;
}

public class Name {
    @Id
    @Column(name = "Id")
    private Long id;

    @OneToOne
    @PrimaryKeyJoinColumn(name = "Id")
    private Person person;

    @Column
    private String first;
    @Column
    private String last;
}

Person person = new Person();
person.setName(new Name("first", "last"));
session.save(person);

We were able to easily setup those 2 entities. But we have to first save the person and then save the name through hibernate. It's very important that we only have to save person.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

似最初 2024-10-08 12:20:13

我也有同样的问题。我尝试将mappedBy条件移动到“辅助”实体,希望在保存主实体时它也会保存这个辅助实体。

保存主实体会生成以下异常(适用于上面的示例):
org.hibernate.id.IdentifierGenerationException:在调用 save() 之前必须手动分配此类的 ids:com.my.Name。

另外,如果我查看配置生成的表,我会发现 Person 表有一个 FK“名称”,它指向 Name 表的 id。使用共享主键的全部目的是避免像这样的 FK 列。

所以将mappedBy移动到辅助表并不是一个解决方案。

I am having the same problem. I tried moving the mappedBy condition to the "secondary" entity hoping that when the main entity will be saved it will also save this secondary entity.

Saving the main entity generated the following exception (adapted to the above example):
org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.my.Name.

Also if I look at the tables generated by my configuration I see that the Person table has a FK "name" which points to the id of the Name table. The whole purpose of using shared primary keys is to avoid FK columns like this one.

So moving the mappedBy to the secondary table is not a solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文