我在休眠@oneToMany中有什么关系的家伙有什么问题:

这是贷款类:

@ManyToOne(cascade=CascadeType.ALL) private users user;

这在用户类中:
    @OneToMany(mappedBy="user",fetch=FetchType.LAZY) private Set<loans> loans=new HashSet<loans>(0);

这里我有插入新贷款的方法:

public static void addLoanToUser(Integer userID,String brand,String model,String registration,String loanStart , String loanEnd){
 Session session = HibernateUtil.getSessionFactory().openSession();
      Transaction transaction = null;
    try {

        transaction = session.beginTransaction();
                    users user = (users) session.load(users.class, userID);
                    Set<loans> loanSet = new HashSet();

                    loans loan = new loans();
                    loan.setBrand(brand);
                    loan.setModel(model);
                    loan.setRegistration(registration);
                    loan.setLoanStart(loanStart);
                    loan.setLoanEnd(loanEnd);
                    loan.setPaydone("no");
                    loanSet.add(loan);
                    user.setLoans(loanSet);

                    session.saveOrUpdate(user);
                    session.save(loan);

        session.getTransaction().commit();

    } catch (HibernateException e) {
        transaction.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }

 }


当我将数据插入数据库时​​,外键始终为NULL。
我试图在堆栈上找到某物,但没有任何帮助。

最佳答案

这是因为在这种情况下,您必须在“密钥持有人”上设置关系,即为“ loan”实体。所以

users user = (users) session.load(users.class, userID);
loans loan = new loans();
..... setup
loan.setUser(user)
session.saveOrUpdate(user);


您确实意识到,如果用户要借新贷款,则可以通过设置全新的user.loans set?来有效地删除该用户(在当前会话中)的其他贷款。 :)我希望银行系统像这样工作:)

关于java - Hibernate添加新元素@oneToMany,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50473880/

10-12 06:24