Issue
Is there any simpler way to delete the records of table with are mapped by @OneToMany and @ManyToOne JPA mapping. Currently I am using PostgreSQL as my database. There are 1000 records ranging from 0 to 999 which I want to delete, and rest I want to keep. As deleting every record with deletion of there references(foreign key) will be very hectic. Just want a simpler way to do this.
Solution
You can always execute a DELETE
query in JPA:
int rowsDeleted = entityManager
.createQuery("DELETE FROM MyEntity WHERE id >= 0 AND id <=999")
.executeUpdate();
If there are foreign keys, you need some extra work:
int childRowsDeleted = entityManager
.createQuery("DELETE FROM MyChildEntity WHERE parent.id >= 0 AND parent.id <=999")
.executeUpdate();
int rowsDeleted = entityManager
.createQuery("DELETE FROM MyEntity WHERE id >= 0 AND id <=999")
.executeUpdate();
If there are many foreign keys, perhaps you can consider JPA cascade remove:
@OneToOne(cascade={CascadeType.REMOVE})
and then entityManager.remove()
each entity but this will have performance implications since you will end up with many DELETE
queries, each deleting a single row.
Answered By - Tasos P.