小编典典

Hibernate-双向@OneToOne

hibernate

我有2个类:User和UserPicture具有1:1的关系。

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;

UserPicture中的“ user”将被加载,而UserPicture中的“ userPicture”则不会加载-我错了吗?

编辑 必须添加,我只是创建一个UserPicture并插入它们(使用现有的userId)-也许我需要在UserPicture中级联“ user”?


阅读 336

收藏
2020-06-20

共1个答案

小编典典

您必须映射您的课程。

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

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