外键中的JPA / Hibernate OneToOne Null

时间:2011-06-17 16:48:48

标签: java hibernate jpa

我有以下两个具有双向OneToOne关系映射的实体,数据访问由Hibernate EntityManager v。“3.5.1-Final”提供。

@Entity
@Table(name = "details")
public class Details {
    private Long id;
    private User user;

    public void setUser(User user) {
        this.user = user;
    }

    @OneToOne  
    @JoinColumn(name="user_id") 
    public User getUser() {
        return user;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }
}

@Entity
@Table(name = "users")
public class User {
private Long id;
private Details details;

public void setDetails(Details details) {
    this.details = details;
}

@OneToOne(mappedBy="user",cascade=CascadeType.ALL)  
public Details getDetails() {
    return details;
}
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
    public Long getId() {
        return id;
    }

    private void setId(Long id) {
        this.id = id;
    }
}

持久性代码:

User user = new User();
Details details = new Details();
user.setDetails(details);

entityManager.persist(user);

然后在两个表中正确插入数据,问题是详细信息表“user_id”中的FK变为空,不确定这里是否缺少。

1 个答案:

答案 0 :(得分:11)

您需要添加details.setUser(user).

user.setDetails(details);仅在User实体中设置外键。 @OneToOne只告诉hibernate如何解释返回的数据(以及如何使用连接获取)。它没有告诉Hibernate要设置哪些外键。