简体   繁体   English

JPA将ID设置为零后保留实体

[英]Jpa persisting an entity after setting id to zero

I have the following three entities 我有以下三个实体

@Entity
class Session {

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval=true)
     @JoinColumn(name="session_id", referencedColumnName="id")
    private List<Testcase> testcases;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval=true)
    @JoinColumn(name="session_id", referencedColumnName="id")
    private List<SessionChart> sessionCharts;
}

@Entity
class SessionChart {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval=true)
    @JoinColumn(name="sessionChart_id", referencedColumnName="id")
    private List<ChartMeasurement> chartMeasurement;

}


@Entity
class ChartMeasurement {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @ManyToOne
    @JoinColumn(name = "testcase_id", nullable=true, referencedColumnName = "id")
    private Testcase testcase;
}

and its corresponding getters and setters. 及其相应的获取器和设置器。 Creating a new session and persisting it with out any session charts and chart measurements works great. 创建一个新会话并在没有任何会话图表和图表度量的情况下将其持久化非常有用。 But I have a save as functionality when I can open a previous saved session from a different user and rename it (change the owner as me) and resave it thus creating a new database record. 但是,当我可以从其他用户打开先前保存的会话并重命名它(将所有者更改为我)并重新保存它,从而创建新的数据库记录时,便具有另存为功能。 I do this by setting id 0 to the entity and all its sub entities, that is Testcases list sessionCharts list and all chartMeasurement entitites inside sessionCharts list. 我通过为实体及其所有子实体设置id 0来做到这一点,即测试用例列表sessionCharts列表和sessionCharts列表中的所有chartMeasurement实体。 But when trying to persist I get the following error 但是当尝试坚持时,出现以下错误

object references an unsaved transient instance - save the transient instance before flushing : ChartMeasurement.testcase -> Testcase

How can I overcome this behavior? 我该如何克服这种行为?

I'm going to assume you are using JPA and thus are using an javax.persistence.EntityManager instance. 我将假设您正在使用JPA,因此正在使用javax.persistence.EntityManager实例。

I would suggest detaching the object before changing the ID's and performing a persist. 我建议在更改ID并执行持久化操作之前先分离对象。

For example, 例如,

entityManager.detach(instanceOfYourObjectHere);

What's happening is that the Session is holding a reference to your object instance and is confused as you have changed the primary keys. 发生的情况是,会话持有对您的对象实例的引用,并且由于您更改了主键而感到困惑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM