Hibernate @ManyToOne only works with CascadeType.ALL
Asked Answered
C

2

11

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

Compliancy answered 20/8, 2013 at 21:54 Comment(0)
G
12

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()

Gaudery answered 20/8, 2013 at 22:4 Comment(4)
This was exactly the right answer, after adding the @Cascade annotation, it worked as expected! thanks alot!Compliancy
Welcome to SO. If one of the answers below fixes your issue, you should accept it (click the check mark next to the appropriate answer). That does two things. It lets everyone know your issue has been resolved, and it gives the person that helps you credit for the assist. See here for a full explanationGaudery
@bellabax How did you come by this solution? Is it described in the hibernate documentation ? Could you please point out an reference where this issue is described in detail, especially why this is happening ? I found this mkyong.com/hibernate/… but it is not very east to understand without looking at the hibernate source.Cardinalate
is write here (docs.jboss.org/hibernate/annotations/3.5/reference/en/…)Gaudery
S
-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);    
Smashed answered 21/8, 2013 at 5:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.