Hibernate @ManyToOne only works with CascadeType.ALL

≡放荡痞女 提交于 2019-11-27 18:05:24

问题


I am using Hibernate 3.3.1 and i would like to create a relation between persons and an assigned company. They should be loosely coupled, but i would like to arrange to create a company via cascade and not explicitly calling saveOrUpdate(newCompany).

I defined the following entities:

class Company
{
   @Id
   Long companyId;
   String name;
}

class Person
{
   @Id
   Long personId;
   String name;
   @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE})
   Company company;
}

inside my dao i am doing the following:

testpers.setCompany (newCompany);
session.saveOrUpdate(testpers);

and i get an exception

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: consearch.model.core.Company

When annotating with "cascade = CascadeType.ALL" it works, but i do not want to also ccade Deletion (e.g. if a Company is removed, then the person should not be removed)

I was wondering that nobody had this problem before Thanks in advance for helping me. Shane


回答1:


Probably you need to enable Hibernate custom @Cascade when using non-JPA Session.saveOrUpdate() method.
Add @Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE) or use Session.persist()




回答2:


i don't feel the mappings are right

class Company
{
@Id
Long companyId;
String name;
@OneToMany(fetch = FetchType.LAZY,mappedBy="company"
@Cascade({CascadeType.SAVE_UPDATE})
List<Person> persons;
}

class Person
{
@Id
Long personId;
String name;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="company_id")
Company company;
}

Set like this now

Company c=new Company();
List<Person> plist=new ArrayList<>();
Person p=new Person();
p.setCompany(c);
plist.add(p);
c.setPersons(plist);
dao.save(c);    


来源:https://stackoverflow.com/questions/18345598/hibernate-manytoone-only-works-with-cascadetype-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!