简体   繁体   中英

Hibernate detached entity passed to persist

None of the similar questions on this site have been able to resolve my problem.

Error: org.hibernate.PersistentObjectException: detached entity passed to persist: healthcheckapi.model.Checks

I am trying to use Hibernate (JPA) to persist two objects to a MYSQL database. "Health" has a oneToMany relationship with "Checks".

Code:

Health Class:

@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;
    }

Checks Class:

@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;
    }

Sample JSON Health Object:

{
    "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
        }
    ]
}

Note that the id's for both objects are auto-generated which I think is part of the problem.

使用CascadeType.MERGE而不是CascadeType.ALL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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