开发者

How to cascade save a simple shared primary key one-to-one mapping in hibernate 3.6

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜