Question

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

Was it helpful?

Solution

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

OTHER TIPS

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);    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top