Delete records older than give date using Spring Data JPA

This tutorial shows how to delete the records older than certain time using Spring Data JPA with out using @Query annotation

For example, if you have following Entity and if you want to delete all the comments older than 7 year, following are the steps

Additional Spring Data JPA Examples :

1) Entity class

package com.kalliphant.samples;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "comment")
public class Comment {

    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "comment_id")
    private Long id;

    @Column(name = "user_name")
    private String userName;

    @Column(name = "data")
    private String data;

    @Column(name = "created_on")
    private Date createdOn;
   //get and set methods


2) CommentRepository Interface

Create the CommentRepository interface with the following method

package com.kalliphant.samples.springdata.jpa;

import org.springframework.transaction.annotation.Transactional;

public interface CommentRepository extends CrudRepository<Comment , Long> {

        * This methods deletes all the records whose 'createdOn' date is less than 'expiryDate'
       @Transactional // Make sure to import org.springframework.transaction.annotation.Transactional
       public void deleteByCreatedOnBefore(Date expiryDate);

NOTE : @Modifying annotation is not required in the above CommentRepository interface, if you are using Spring Data JPA 1.7 or newer

3)Java class

Following is the code to compute the expiry date and to call the repository delete method

		 * Calculate the expiry date
		Calendar cal = Calendar.getInstance();
		Date today = cal.getTime();
		cal.add(Calendar.YEAR, -7);
		Date expiryDate = cal.getTime();

		 * Call the repository method to delete all the records older than give
		 * date

Additional Spring Data JPA Examples :


    1. Hello vvk,

      You can do by adding the following method in the CommentRepository

      @Query(“delete from Comment where rownum < = ?1")
      void deleteFixedRecordsAtAtime(int count);

      And call as follows

Comments are closed.