Mahmoud Saleh
Mahmoud Saleh

Reputation: 33625

Can't delete element from @OneToMany collection

i have an entity Entity1 that have one to many relation with Entity2 as follows:

1- Entity1:

@Entity
@Table(name = "Entity1", catalog = "mydb")
public class Entity1 implements java.io.Serializable {

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "entity1", cascade = javax.persistence.CascadeType.ALL)
  @OrderBy("id")
  private Set<Entity2> collection = new HashSet<Entity2>(
            0);

}

2- Entity2: (equals and hashcode method overridden)

@Entity
@Table(name = "entity2", catalog = "advertisedb")
public class Entity2 implements java.io.Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "pkid", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    private long id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "fk_entity1", nullable = false)
    private Entity1 entity1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "apid", nullable = false)
    private Entity3 entity3;

}

3- Here's how i am removing the entity from the collection:

    entity1Obj.getEntity2().remove(entity2);
    log.debug("size after remove: "+ entity1Obj.getEntity2().size()); // size decreases correctly, so the entity is removed from the collection
    entity1Dao.updateEntity1(entity1);

4- DAO method:

   public void updateEntity1(Entity1 entity1) {
        getCurrentSession().update(getCurrentSession().merge(entity1));
    }

Problem: what i get in the console, is a select query for the entity2 that should be removed, and no delete query, and nothing is getting deleted.

please advise how to fix this issue.

Upvotes: 3

Views: 2274

Answers (1)

Mahmoud Saleh
Mahmoud Saleh

Reputation: 33625

i replaced cascade = CascadeType.ALL with orphanRemoval = true and it works fine now.

Upvotes: 4

Related Questions