0
votes

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.

2

2 Answers

0
votes

I am not an expert with Hibernate, but according to Documentation for merge() here

The given instance does not become associated with the session.

I would suggest to fetch Entity in current Session, change fields' values and then flush it.

Or, In case of new Entity -- save() it.

Also. As far as I know, calling Transaction.commit() performs session flushing, so no need to do it manually after

0
votes

I have solved the issue myself. Answering my question so that it can help others.

The issue was with Salutation object under User. Salutation was initialized having its primary key 'id' being null. So, when trying to flush on session object Salutation's id was found to be null and because of this it was throwing this error. Setting null to Salutation object solved my issue.