I have 2 classes
@Entity
@Table(name = "user")
public class User
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
@Cascade({CascadeType.ALL})
private Collection<Book> userBooks;
}
@Entity
@Table(name = "books")
public class Book
@Id
@Column(name = "id")
@GeneratedValue
private int id;
@ManyToOne
private User user;
}
here some more code:
User user = new User(); user.setUserName("Gleeb"); user.setUserPassword("gleeb");
Book book = new Book();
book.setTitle("some book ");
book.setbookType(1);
user.addUserbook(book);
userService.save(user);
i am trying to create a new user and add a new book to it.
when i save the user
session.saveOrUpdate(user);
the user is saved, the book is saved
but in the book table, the user_id is not set. and is left NULL.
why is that.
thanks.
You didn’t show your code, but the join table was probably not populated because you forgot to initialize the user field of the book. in a bidirectional association, the owner side is the side which doesn’t have the mappedBy attribute, and it’s this side that JPA uses to know id the association exists or not.