Mourad Lamkas
Mourad Lamkas

Reputation: 83

jpa hibernate: detached entity passed to persist

Detached entity passed to persist turned my life into hell, it's been two days since i got this problem and I've tried everything in this website and nothing works. So i have two tables "modules" and "attestations", and i have a list of module's titles and what i'm doing is taking that title and retrieve the module and for each module i want to put the attestations that i already created. in my example i'm using ManyToMany relationship

so i have theses following classes :

classe attestations :

@Entity
@Table(name = "edep_attestations")
public class Attestation implements Serializable {
private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
       private Long id;
       private String title;
       ...
       @ManyToMany(mappedBy="attestations")
       private Set<Module> modules = new HashSet<>();

       // getters and setters
}

classe modules :

@Entity
@Table(name = "edep_modules")
public class Module implements Serializable {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     protected Long id;
     private String title; 
     ...
     @ManyToMany(fetch = FetchType.EAGER,cascade = {CascadeType.MERGE})
     private Set<Attestation> attestations = new HashSet<>();
    // getters and setters 
}

and this is the method that i'm using in my bean

public String create(){
    Module m = null;
    this.attestationsService.create(attestation);
    for (String title : moduleTitles) {
            m = modulesService.getModulebyTitle(title);
            m.getAttestation().add(attestation); 
            this.modulesService.create(m);
    }
    return "success";
}

class modulesService, create method:

public void create(E object) throws Exception {
    em.clear();
    em.persist(object);
    em.flush();
}

Upvotes: 2

Views: 1675

Answers (1)

Mourad Lamkas
Mourad Lamkas

Reputation: 83

I solved this by removing the @GeneratedValue annotation. It looks like no other option was working for me (auto or identity).
So what I do instead: I retrieve the max id of my table, increment it by one, and set it manually to my entity. When I then persist the object it's working perfectly.

Upvotes: 2

Related Questions