jpa和hibernate比较时间戳与特定天数。

huangapple go评论69阅读模式
英文:

jpa and hibernate compare timestamp to a certain number of day

问题

我想在jpa中的某些天后删除一些行

@Query("DELETE FROM TABLE t WHERE lastChange > :numberOfDays")
void delete(@Param("numberOfDays") int numberOfDays);

`numberOfDays`可能是10天虽然`numberOfDays`是一个整数,`lastChange`是一个时间戳日期时间)。

@Entity(name = "Table")
public class TableEntity
{
   @Id
   private String id;
   @UpdateTimestamp
   private Timestamp lastChange;
}
英文:

I want to delete some rows after some days in jpa.

@Repository
public interface JpaTableRepository extends JpaRepository<TableEntity, String>
{
   @Query("DELETE FROM TABLE t WHERE lastChange > :numberOfDays")
   void delete(@Param("numberOfDays") int numberOfDays);
}

numberOfDays may be 10 Days. While numberOfDaysis a int, lastChange is a TimeStamp (datetime).

@Entity(name = "Table")
public class TableEntity
{
   @Id
   private String id;
   @UpdateTimestamp
   private Timestamp lastChange;
}

答案1

得分: 1

日期操作在JPA中受到限制,但您可以使用Java方法。

服务:

int numberOfDays = 10;
LocalDateTime dateTimeMinusTenDays = LocalDateTime.now().minusDays(numberOfDays);

repository.delete(dateTimeMinusTenDays);

存储库:

@Query("DELETE FROM TABLE t WHERE lastChange > :startingLimitDateTime")
void delete(@Param("startingLimitDateTime") LocalDateTime startingLimitDateTime);

(需要将lastChange的类型更改为java.time.LocalDateTime

英文:

Date operations is limited in JPA, but you could use Java methods.

Service :

int numberOfDays = 10;
LocalDateTime dateTimeMinusTenDays = LocalDateTime.now().minusDays(numberOfDays);

repository.delete(dateTimeMinusTenDays);

Repository :

@Query("DELETE FROM TABLE t WHERE lastChange > :startingLimitDateTime")
void delete(@Param("startingLimitDateTime") LocalDateTime startingLimitDateTime);

(It requires to change lastChange type to a java.time.LocalDateTime)

huangapple
  • 本文由 发表于 2023年7月13日 15:18:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76676830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定