Hibernate - bidirectional @OneToOne

user1731299 picture user1731299 · Oct 24, 2012 · Viewed 20.7k times · Source

I have 2 classes: User and UserPicture which have a 1:1 relationship.

public class User {
     @Id
     @GeneratedValue(strategy=GenerationType.AUTO)
     @Column(name="id", nullable = false, unique = true)
 private int id;

     private String firstname;

     private String lastname;

     @OneToOne
     @JoinColumn(name = "picture") //field named "picture" in the database
     private UserPicture userPicture;

     ..
}


public class UserPicture {

     @Id
     @GeneratedValue(strategy=GenerationType.AUTO)
     @Column(name="id", nullable = false, unique = true)
     private int id;

     private Blob image;

     @OneToOne
     @JoinColumn(name = "user")
     User user;

'user' in UserPicture will be loaded but 'userPicture' in User not - what did Im wrong?

EDIT Have to add that Im just create a UserPicture and insert them (with existing userId) - maybe I need to cascade 'user' in UserPicture?

Answer

Pigueiras picture Pigueiras · Oct 24, 2012

You have to map your classes.

public class User {
    ...
    @OneToOne (mappedBy="user")
    private UserPicture userPicture;
    ...
}

public class UserPicture {
    ...
    @OneToOne
    @JoinColumn (name="user")
    private User user;
    ...
}