Home > Net >  Simpler way to delete JPA mapped tables records
Simpler way to delete JPA mapped tables records

Time:09-28

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.

CodePudding user response:

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.

CodePudding user response:

Got this with introducing @DeleteMapping, and it worked without even using " @OnDelete(action = OnDeleteAction.CASCADE)" this annotation above the mapped variable declaration in the child class [https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/#get-paginated-posts-get-postspage0size2sortcreatedatdesc], We can follow this link to get a complete overview.

 @DeleteMapping("/posts/{postId}")
    public ResponseEntity<?> deletePost(@PathVariable Long postId) {
        return postRepository.findById(postId).map(post -> {
            postRepository.delete(post);
            return ResponseEntity.ok().build();
        }).orElseThrow(() -> new ResourceNotFoundException("PostId "   postId   " not found"));
    }
  • Related