【问题标题】:object references an unsaved transient instance - save the transient instance before flushing: com.example.model.Salutation对象引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:com.example.model.Salutation
【发布时间】: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


    【解决方案1】:

    我不是 Hibernate 专家,但根据 merge() here 的文档说明

    给定实例未与会话关联。

    我建议在当前Session 中获取Entity,更改字段的值,然后刷新它。

    或者,如果是新实体 -- save() 它。

    还有。据我所知,调用Transaction.commit()会执行会话刷新,所以之后不需要手动进行

    【讨论】:

    • 感谢您的意见@Eugene。我很感激。
    【解决方案2】:

    我自己解决了这个问题。回答我的问题,以便它可以帮助其他人。

    问题在于用户下的称呼对象。称呼已初始化,其主键“id”为空。因此,当尝试刷新会话对象时,Salutation 的 id 被发现为空,因此引发了此错误。将 null 设置为 Salutation 对象解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 2015-09-27
      • 2021-03-03
      • 2013-11-30
      • 1970-01-01
      • 2012-02-27
      相关资源
      最近更新 更多