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
By providing @OneToMany(cascade = {CascadeType. ALL}) , it tells Hibernate to save them to the database while saving the parent object. Save this answer.
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.
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.
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();
}
You should use the CascadeType.PERSIST or CascadeType.ALL
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With