Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object references an unsaved transient instance : save the transient instance before flushing [duplicate]

Tags:

java

hibernate

I have two entities: PlayerProfileEntity & UserInfoEntity I have a join on userInfoEntity & PlaterProfileEntity and saving my record in database like this:

Session session = sessionFactory.openSession();
Transaction tr = session.beginTransaction();
Criteria crit = session.createCriteria(PlayerProfileEntity.class);
player.setUserId(new UserInfoEntity());
player.getUserId().setAddress(user.getUserId().getAddress());
session.save(player);
tr.commit();

I used this assosiation in my PlayerProfileEntity class

@ManyToOne (fetch = FetchType.LAZY)
@Cascade({CascadeType.REFRESH})
@JoinColumn(name="userid")

I am getting this error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save     the transient instance before flushing: com.shared.entity.UserInfoEntity

Note : If i use CascadeType.All, i get this error:

Cannot add or update a child row: a foreign key constraint fails

Any idea how can i solve this

Thanks

like image 939
user1226162 Avatar asked Apr 23 '12 09:04

user1226162


People also ask

How do you fix the Hibernate object references an unsaved transient instance save the transient instance before flushing error?

By providing @OneToMany(cascade = {CascadeType. ALL}) , it tells Hibernate to save them to the database while saving the parent object. Save this answer.

What is transient instance in Java?

1. Transient State: A New instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate: UserDetail user = new UserDetail(); user.setUserName("Dinesh Rajput"); // user is in a transient state. Popular Tutorials.

Can an object in hibernate go from persistence state to transient state?

No, it's not possible. Transient object are objects with no reference in database. Persistent and detached on the other hand have representation in database (are persisted). Detached object is persisted, but for this object hibernate session is closed.


2 Answers

public void savePlayerMethod(PlayerInfoEntity player){

if(player == null){
   player = new PlayerInfoEntity();
}
player.setUserId(getSavedUserInfo());
Session session = SessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(userInfo);
transaction.committ();
}

public UserInfoEntity getSavedUserInfo(){
UserInfoEntity userInfo = new UserInfoEntity();
Session session = SessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(userInfo);
transaction.committ();
}
like image 199
PVR Avatar answered Sep 24 '22 18:09

PVR


You should use the CascadeType.PERSIST or CascadeType.ALL

like image 29
Marko Topolnik Avatar answered Sep 21 '22 18:09

Marko Topolnik