JPA / Hibernate OneToOne Null in a foreign key

I have the following two objects with OneToOne bidirectional relational mapping, data access is provided by 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;
    }
}

and

@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;
    }
}

Save code:

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

entityManager.persist(user);

Then the data is inserted correctly in both tables, the problem is that the FK in the details table "user_id" gets null, I'm not sure what is missing here.

+5
source share
1 answer

you need to add details.setUser(user).

user.setDetails(details); . @OneToOne hibernate, ( - ). Hibernate, .

+10

All Articles