Delete records from more than 1 year ago

前端 未结 4 655
说谎
说谎 2021-01-18 02:26

I\'m saving twitter tweets in my database with spring JPA Repositories. The date of the tweet is saved as Datetime in the MySQL db. Now I want to delete all tweets that are

4条回答
  •  攒了一身酷
    2021-01-18 02:58

    For this you need 2 steps. First of all you need a method that will take as a parameter the date of which you want to delete the messages and you dont need tha @Query annotation at all.

    So in your repository you must have something like

        @Modifying
        public void deleteByCreatedAtBefore(Date expiryDate);
    

    Now in your service method, you will calculate the Date and pass it on like this

        public void performTweetCleanup(){
           //calculate date
           Calendar cal = Calendar.getInstance();
           Date today = cal.getTime();
           cal.add(Calendar.YEAR, -1);
           Date previousYear = cal.getTime();
    
           //call the method
           MyTweeterRepository.deleteByCreatedAtBefore(previousYear);
         }
    

提交回复
热议问题