Robert Strauch
Robert Strauch

Reputation: 12876

Deleting entries from @CollectionTable with @ElementCollection using JPA

I have an entity like the following. It is simplified as I cannot post the original code but it should be sufficient to get the idea.

The point is:

Using an EntityManager I can delete entries in the my_table table. So far so good. Now I also need to delete entries in my_mapping_table but I don't have any idea how to do that.

Using the above EntityManager probably won't work because this field is not an Entity.

Any ideas how I can delete entries from that table or truncate it?

@Data
@NoArgsConstructor
@Entity
@Builder
@AllArgsConstructor
@Table(name = "my_table")
public class MyTable {

    @ElementCollection(targetClass = SomeClass.class)
    @CollectionTable(name = "my_mapping_table", joinColumns = @JoinColumn(name = "id_1", referencedColumnName = "id_2"))
    @Column(name = "someclass_enum")
    @Convert(converter = SomeClassConverter.class)
    private Set<SomeClass> setOfSomeClass = new HashSet<>();
}

Upvotes: 0

Views: 982

Answers (1)

Ken Chan
Ken Chan

Reputation: 90417

@ElementCollection is managed through its parent entity. To remove them , you have to get its parent entity first and then simply clear the collection.

First create a method on MyTable to clear all of its ElementCollection :

@Entity
public class MyTable {

    public void removeAllSomeClass(){
          this.setOfSomeClass.clear();
    }
}

To delete all ElementCollection for a particular MyTable record :

MyTable row1 = entityManager.find(MyTable.class,1);
row1.removeAllSomeClass();

So to truncate all entries from my_mapping_table :

for(MyTable tbl : em.createQuery("from MyTable", MyTable.class).getResultList()){
  tbl.removeAllSomeClass();
}

Upvotes: 1

Related Questions