Hibernate添加了新元素@oneToMany

时间:2018-05-22 18:01:41

标签: java hibernate

错误的家伙我在休眠@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。 我试图在堆栈上找到......但没有任何帮助。

1 个答案:

答案 0 :(得分:1)

因为你必须在&#34;密钥持有者&#34;上设置关系。在您的情况下是loan实体。所以

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

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