Adding a one-to-one relationship with shared primary key can become a difficult task if the main table key is an auto-generated one.

Even the Hibernate Annotations documentation example only works with not auto-generated id, if you try to use an auto incremental id, for example, 

it’s impossible to persist the 2 tables at the same time.

Surfing on the net I’ve seen some ppl with this kind of problem (I suppose one-to-one relationships are not so common, don’t know why) and most of ppl use the foreign-key approach that works ok but it’s not clean from my point of view, so I wanted to find a solution for my case.

The original example from the Hibernate Annotations Documentation is:

@Entity
public class Body {

    @Id
    public Long getId() { return id; }

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    public Heart getHeart() {
        return heart;
    }

    …

}

 

@Entity
public class Heart {

    @Id
    public Long getId() { … }

}

As you can see this as not auto generated id and will not work just putting the @GeneratedValue annotation.

The final solution is:

@Entity
public class Body {

    @Id
    @GeneratedValue(strategy = IDENTITY)
    public Long getId() { return id; }

    @OneToOne(cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    public Heart getHeart() {
        return heart;
    }

    …

}

@Entity
public class Heart {

    @Id
    @GeneratedValue(generator=”foreign”) 
    @GenericGenerator(name=”foreign”, strategy = “foreign”, parameters = {@Parameter(name=”property”, value=”body”)})
    public Long getId() { …}

    @OneToOne(mappedBy=”heart”)
    public Body getBody() { … }

}

Now all works fine for me.
Thanks
Demetrio
, , , , , ,