# Entity must be managed to call remove



## Yuha (25. Jun 2015)

Ich habe eine Entity

```
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package persontest;


import java.io.Serializable;
import java.util.List;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;


@Entity
@Table(name = "person")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Person.findAll", query = "SELECT p FROM Person p"),
    @NamedQuery(name = "Person.findById", query = "SELECT p FROM Person p WHERE p.id = :id"),
    @NamedQuery(name = "Person.findByCreatedAt", query = "SELECT p FROM Person p WHERE p.createdAt = :createdAt"),
    @NamedQuery(name = "Person.findByModifiedAt", query = "SELECT p FROM Person p WHERE p.modifiedAt = :modifiedAt"),
    @NamedQuery(name = "Person.findByDeletedAt", query = "SELECT p FROM Person p WHERE p.deletedAt = :deletedAt"),
    @NamedQuery(name = "Person.findByActiveCode", query = "SELECT p FROM Person p WHERE p.activeCode = :activeCode"),
    @NamedQuery(name = "Person.findByEnabled", query = "SELECT p FROM Person p WHERE p.enabled = :enabled"),
    @NamedQuery(name = "Person.findByGernder", query = "SELECT p FROM Person p WHERE p.gernder = :gernder"),
    @NamedQuery(name = "Person.findByFirstname", query = "SELECT p FROM Person p WHERE p.firstname = :firstname"),
    @NamedQuery(name = "Person.findByLastname", query = "SELECT p FROM Person p WHERE p.lastname = :lastname"),
    @NamedQuery(name = "Person.findByEmail", query = "SELECT p FROM Person p WHERE p.email = :email"),
    @NamedQuery(name = "Person.findByPassword", query = "SELECT p FROM Person p WHERE p.password = :password")})
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @Column(name = "created_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Column(name = "modified_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date modifiedAt;
    @Column(name = "deleted_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date deletedAt;
    @Column(name = "active_code")
    private String activeCode;
    @Basic(optional = false)
    @Column(name = "enabled")
    private boolean enabled;
    @Basic(optional = false)
    @Column(name = "gernder")
    private short gernder;
    @Basic(optional = false)
    @Column(name = "firstname")
    private String firstname;
    @Basic(optional = false)
    @Column(name = "lastname")
    private String lastname;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @OneToMany(mappedBy = "createdBy")
    private List<Person> personList;
    @JoinColumn(name = "created_by", referencedColumnName = "id")
    @ManyToOne
    private Person createdBy;
    @OneToMany(mappedBy = "deletedBy")
    private List<Person> personList1;
    @JoinColumn(name = "deleted_by", referencedColumnName = "id")
    @ManyToOne
    private Person deletedBy;
    @OneToMany(mappedBy = "modifiedBy")
    private List<Person> personList2;
    @JoinColumn(name = "modified_by", referencedColumnName = "id")
    @ManyToOne
    private Person modifiedBy;


    public Person() {
    }


    public Person(Integer id) {
        this.id = id;
    }


    public Person(Integer id, Date createdAt, boolean enabled, short gernder, String firstname, String lastname) {
        this.id = id;
        this.createdAt = createdAt;
        this.enabled = enabled;
        this.gernder = gernder;
        this.firstname = firstname;
        this.lastname = lastname;
    }


    public Integer getId() {
        return id;
    }


    public void setId(Integer id) {
        this.id = id;
    }


    public Date getCreatedAt() {
        return createdAt;
    }


    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }


    public Date getModifiedAt() {
        return modifiedAt;
    }


    public void setModifiedAt(Date modifiedAt) {
        this.modifiedAt = modifiedAt;
    }


    public Date getDeletedAt() {
        return deletedAt;
    }


    public void setDeletedAt(Date deletedAt) {
        this.deletedAt = deletedAt;
    }


    public String getActiveCode() {
        return activeCode;
    }


    public void setActiveCode(String activeCode) {
        this.activeCode = activeCode;
    }


    public boolean getEnabled() {
        return enabled;
    }


    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }


    public short getGernder() {
        return gernder;
    }


    public void setGernder(short gernder) {
        this.gernder = gernder;
    }


    public String getFirstname() {
        return firstname;
    }


    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }


    public String getLastname() {
        return lastname;
    }


    public void setLastname(String lastname) {
        this.lastname = lastname;
    }


    public String getEmail() {
        return email;
    }


    public void setEmail(String email) {
        this.email = email;
    }


    public String getPassword() {
        return password;
    }


    public void setPassword(String password) {
        this.password = password;
    }


    @XmlTransient
    public List<Person> getPersonList() {
        return personList;
    }


    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }


    public Person getCreatedBy() {
        return createdBy;
    }


    public void setCreatedBy(Person createdBy) {
        this.createdBy = createdBy;
    }


    @XmlTransient
    public List<Person> getPersonList1() {
        return personList1;
    }


    public void setPersonList1(List<Person> personList1) {
        this.personList1 = personList1;
    }


    public Person getDeletedBy() {
        return deletedBy;
    }


    public void setDeletedBy(Person deletedBy) {
        this.deletedBy = deletedBy;
    }


    @XmlTransient
    public List<Person> getPersonList2() {
        return personList2;
    }


    public void setPersonList2(List<Person> personList2) {
        this.personList2 = personList2;
    }


    public Person getModifiedBy() {
        return modifiedBy;
    }


    public void setModifiedBy(Person modifiedBy) {
        this.modifiedBy = modifiedBy;
    }
    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }


    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Person)) {
            return false;
        }
        Person other = (Person) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }


    @Override
    public String toString() {
        return "persontest.Person[ id=" + id + " ]";
    }
    
}
```

Ich möchte wenn der Vater gelöscht wird das die entsprechenden Verweise der Kinder auf null gesetzt werden.
Zum Testen haben ich mir eine Main - Klasse geschrieben.

```
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package persontest;


import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;


public class Main {


     public static void main(String[] a) { 
            EntityManagerFactory factory;
            EntityManager em = null;
         
            Person person1 = new Person();
            
            person1.setCreatedAt(new Date());
            person1.setFirstname("Huge");
            person1.setLastname("Boss");
            person1.setEmail("Huge@google.de");
            person1.setFirstname("HugeBoss");
            
            Person person2 = new Person();
            
            person2.setCreatedAt(new Date());
            person2.setCreatedBy(person1);
            person2.setFirstname("Kevin");
            person2.setLastname("Klein");
            person2.setEmail("klein@google.de");
            person2.setFirstname("KevinKlein");            
            
            try {
                factory = Persistence.createEntityManagerFactory("pu");
                em = factory.createEntityManager();
                
                em.getTransaction().begin();
                
                em.persist(person1);
                em.persist(person2);
                
                em.getTransaction().commit();                
            } catch( Exception e ) {
                System.out.println(e);
                em.getTransaction().rollback();
            }
            
            try {
                factory = Persistence.createEntityManagerFactory("pu");
                em = factory.createEntityManager();
                
                em.getTransaction().begin();
                for (int i=0; i<person1.getPersonList().size(); i++) {
                    person1.getPersonList().get(i).setCreatedBy(null);
                }
                em.remove(person1);
                
                em.getTransaction().commit();                
            } catch( Exception e ) {
                System.out.println(e);
                em.getTransaction().rollback();
            }
         
     }
}
```

Beim löschen wird mir aber gesagt


> java.lang.IllegalArgumentException: Entity must be managed to call remove: persontest.Person[ id=25 ], try merging the detached and try the remove again.



Ich weis nur nicht was hier gerad schief läuft.


----------



## stg (26. Jun 2015)

person1 ist detached, in dem Moment, wenn du remove() aufrufen willst. Das funktioniert so nicht. Remove() kannst du nur auf managed Instanzen anwenden. Deswegen ja der Hinweis mit dem merge...


```
em.remove(em.merge(person1));
```


----------

