Hibernate将一本书添加到用户

时间:2016-04-08 08:24:28

标签: java hibernate

我在r ModuleNameUser之间建立了多对多关系。现在,我想将现有书籍添加到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);
    }

2 个答案:

答案 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);