I have two model class, User and Salutation as below. Foreign key (salutation_id) in User table is optional. To save User object when I flush on session object right after merge, I am getting below error.
object references an unsaved transient instance - save the transient instance before flushing: com.example.model.Salutation
Data in table Salutation have been inserted independent of User table. When I am trying to save User object having salutation_id as null, it throws this error.
Any help would be appreciable.
@Entity
@Table(name = "user")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(unique = true, nullable = false)
private String userName;
@ManyToOne
@JoinColumn(name = "salutation_id")
private Salutation salutationRef;
//Getter and Setter
}
@Entity
@Table(name = "salutation")
public class Salutation implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ElementCollection
@LazyCollection(LazyCollectionOption.FALSE)
@OneToMany(mappedBy = "salutationRef")
private List<Salutation> salutations;
//Getter and Setter
}
public Object create(Object object) {
Session session = sessionFactory.getCurrentSession();
Transaction txn = session.beginTransaction();
try {
object = (Object) session.merge(object);
session.flush(); //Getting error at this line object references an unsaved transient instance - save the transient instance before flushing: com.example.model.Salutation
txn.commit();
} catch (Exception e) {
txn.rollback();
e.printStackTrace();
}
return object;
}
Thanks for your help.