【发布时间】:2017-04-12 18:50:26
【问题描述】:
我有两个模型类,用户和称呼如下。用户表中的外键(salutation_id)是可选的。为了在合并后立即刷新会话对象时保存用户对象,我遇到了错误。
对象引用了一个未保存的瞬态实例 - 在刷新之前保存瞬态实例:com.example.model.Salutation
表 Salutation 中的数据已独立于用户表插入。当我尝试将 salutation_id 为 null 的用户对象保存时,它会引发此错误。
任何帮助都将不胜感激。
@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;
}
感谢您的帮助。
【问题讨论】:
标签: java json hibernate spring-mvc