Java – object references an unsaved transient instance : save the transient instance before flushing

hibernatejava

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

Best Solution

The TransientObjectException comes whenever you try to save the Object without saving the appropriate Joins.You have to save the UserInfoEntity first and afterwards you can save your PlayerInfoEntity class.

player.setUserId(new UserInfoEntity());

By using this you are assigning particular UserInfoEntity to PlayerInfoEntity. But UserInfoEntity does not have any ID. How would both get mapped ? That is why the exception is coming.

Hope it would help you.

Related Question