【问题标题】:Hibernate detached entity passed to persist传递给持久化的休眠分离实体
【发布时间】:2018-09-09 08:24:35
【问题描述】:

本网站上的类似问题都无法解决我的问题。

错误: org.hibernate.PersistentObjectException:分离的实体传递给持久化:healthcheckapi.model.Checks

我正在尝试使用 Hibernate (JPA) 将两个对象持久保存到 MYSQL 数据库。 “健康”与“检查”具有一对多关系。

代码:

健康类:

@Entity
@Table(name="health")
public class Health {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String server;
    private String description;
    private String timestamp;
    private String offset;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "health")
    private List<Checks> checks;

    public Health() {

    }

    public Health(int id, String server, String description, String timestamp, String offset, List<Checks> checks) {

        this.server = server;
        this.description = description;
        this.timestamp = timestamp;
        this.offset = offset;
        this.checks = checks;
    }

检查类:

@Entity
@Table(name="checks")
public class Checks {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private int status;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "healthid", referencedColumnName="id")
    private Health health;

    public Checks() {

    }

    public Checks(String name, int status) {

        this.name = name;
        this.status = status;
    }

示例 JSON 健康对象:

{
    "server": "Server18",
    "description": "Fine",
    "timestamp": "00:02:30",
    "offset": "00:01:00",
    "checks": [
        {   "id": "1",
            "name": "cpu",
            "status": 90
        },
        {
             "id": "2",
            "name": "memory",
            "status": 88
        },
        {
             "id": "3",
            "name": "apacheService",
            "status": 76
        }
    ]
}

请注意,这两个对象的 id 都是自动生成的,我认为这是问题的一部分。

【问题讨论】:

  • 您不认为发布持久性的实际代码可能会有所帮助吗?包括显示各种对象在持久化点的状态...

标签: java mysql hibernate jpa


【解决方案1】:

使用CascadeType.MERGE 代替CascadeType.ALL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-05
    • 2017-09-04
    • 2013-01-17
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多