Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

many to one - Hibernate @ManyToOne only works with CascadeType.ALL

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...