If the goal is to have a shared primary key , what about it (inspired by the Java Persistence With Hibernate sample and tested in a pet database):
@Entity public class User { @Id @GeneratedValue private Long id; @OneToOne(cascade = CascadeType.ALL) @PrimaryKeyJoinColumn private Address shippingAddress;
This is the "parent" class, which is first inserted and receives the generated identifier. Address as follows:
@Entity public class Address implements Serializable { @Id @GeneratedValue(generator = "myForeignGenerator") @org.hibernate.annotations.GenericGenerator( name = "myForeignGenerator", strategy = "foreign", parameters = @Parameter(name = "property", value = "user") ) @Column(name = "ADDRESS_ID") private Long id; @OneToOne(mappedBy="shippingAddress") @PrimaryKeyJoinColumn User user;
With the above objects, it seems to look as expected:
User newUser = new User(); Address shippingAddress = new Address(); newUser.setShippingAddress(shippingAddress); shippingAddress.setUser(newUser);
When saving Address value of the primary key that is inserted matches the primary key value of the User instance referenced by the User property.
Downloading only User or Address also works.
Let me know if I missed something.
PS: Strictly answer the question, according to Primary keys through OneToOne relationships :
JPA 1.0 does not allow @Id on OneToOne or ManyToOne, but JPA 2.0 does.
But , a version of Hibernate compatible with JPA 1.0
allows you to use the @Id annotation to display OneToOne or ManyToOne *.
I could not get this to work with Hibernate EM 3.4, though (it worked with Hibernate EM 3.5.1, i.e. with the implementation of JPA 2.0). Maybe I did something wrong.
In any case, using a shared primary key seems to provide the right solution.