I have the following two entities with a bi-directional OneToOne 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;
}
}
Persistence code:
User user = new User();
Details details = new Details();
user.setDetails(details);
entityManager.persist(user);
Data is then inserted correctly in both tables, the problem is that FK in details table "user_id" gets null, not sure whats missing here.
you need to add details.setUser(user).
user.setDetails(details);
only set the foreign key in the User entity. the @OneToOne
only tells hibernate how to interpret the returned data (and how to fetch - using joins). It doesn't tell Hibernate which foreign keys to set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With