Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA / Hibernate OneToOne Null in foreign key

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.

like image 334
Ellead Avatar asked Jun 17 '11 16:06

Ellead


1 Answers

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.

like image 83
iliaden Avatar answered Oct 13 '22 02:10

iliaden