我在r ModuleName
和User
之间建立了多对多关系。现在,我想将现有书籍添加到Books
中的现有用户,但每次执行此操作时,都会在User_Books
表中创建一个空的新用户。
User
用户:
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Books book = new Books();
book.setBookshareId(bookshareId);
User user1 = new User();
user1.setUser_id(userID);
user1.getBooks().add(book);
session.save(user1);
tx.commit();
书籍:
@Entity
@Table(name="tblUser")
public class User implements Serializable{
@Id
@Column(name = "Id",unique = true,nullable = false)
@GeneratedValue(strategy=GenerationType.AUTO)
private int Id;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@ManyToMany(mappedBy="user")
private List<Books> books = new ArrayList<Books>();
public void addBooks(Books book) {
this.books.add(book);
}
@Mohamed Nabli 当我执行它时它找到它们但是当我查看User_Books时我什么都没有。
@ManyToMany
@JoinTable(name = "User_Books",
joinColumns = { @JoinColumn(name = "Books_id")},
inverseJoinColumns = { @JoinColumn(name = "User_id")})
private List<User> user = new ArrayList<User>();
public void addUser(User user) {
this.user.add(user);
}
答案 0 :(得分:1)
我希望这会奏效,
您拥有数据库中的用户和书籍,不要使用new来创建用户,您必须直接从数据库中获取它。
将此行添加到User Class的ManyToMany批注
@ManyToMany(mappedBy="user",cascade = {CascadeType.ALL})
private List<Books> books = new ArrayList<Books>();
试试这个:
Books book = (Books) session.get(Books.class, book_id);
User user = (User) session.get(User.class, user_id);
List<Books> books=user.getBooks();
books.add(book);
user.setBooks(books);
session.saveOrUpdate(user);
答案 1 :(得分:1)
我找到了解决方案:)
Books book = (Books) session.get(Books.class, book_id);
User user = (User) session.get(User.class, user_id);
List<User> users=book.getUser();
users.add(user);
book.setUser(users);
session.saveOrUpdate(book);