Hibernate如何保存ManyToOne

时间:2012-09-04 01:34:02

标签: hibernate transactions

我有两个实体EquipementCompany,如下所示:

public class Equipement{
  String type ;
  Company company ;

  @ManyToOne(cascade = CascadeType.ALL)
  public Company getCompany(){
    return this.company ;
  }
}

public class Company{
  // fields getters setters ..
}

每个Equipement都是从Company购买的,我需要创建Company,然后将其注入Equipement

Session session = SessionFactory.openSession() ;
Transaction tx = session.beginTransaction() ;

Equipement equipement = new Equipement() ;
Company company = new company() ;
equipement.setCompany(company) ;
session.save(equipement) ;

tx.commit() ;
session.close() ;

并且给我一个例外

TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: org.marsamaroc.mmapp.domain.Company

1 个答案:

答案 0 :(得分:0)

尝试

public class Company 
{
    @OneToMany(cascade = CascadeType.ALL)
    public Set<Equipement> getEquipements() { ... }
}

...
Session session = SessionFactory.openSession() ;
Transaction tx = session.beginTransaction() ;

Equipement equipement = new Equipement() ;
Company company = new company() ;
equipement.setCompany(company) ;

// Save should cascade (i.e. "equipment" should be saved too).
session.save(company) ;

tx.commit() ;
session.close() ;
...
用英语写的,它是“装备”,没有额外的“e”(如果你在意的话!)。