简体   繁体   English

通过 Spring Boot JPA + Postgresql + H2 执行间隔

[英]Execute interval through Spring Boot JPA + Postgresql + H2

I am trying to create a JPA Repository Query in Spring Boot.我正在尝试在 Spring Boot 中创建一个 JPA 存储库查询。

  • I am using spring-data-jpa 2.1.5, spring-boot 2.1.3, postgresql driver 42.2.5, h2database 1.4.200, Java 1.8我正在使用 spring-data-jpa 2.1.5、spring-boot 2.1.3、postgresql 驱动程序 42.2.5、h2database 1.4.200、Java 1.8

My conditions are :我的条件是:

  • I have to use PostgreSQL for production and H2 for unit (integration) tests.我必须使用 PostgreSQL 进行生产,使用 H2 进行单元(集成)测试。
  • I should not use native query (postgres x h2).我不应该使用本机查询(postgres x h2)。
  • I need to get customer records from customer's table我需要从客户的表中获取客户记录
  • But only the Customers that registered at least 24 hours before the current date.但仅限于在当前日期前至少 24 小时注册的客户。
  • So I mean DB date.所以我的意思是数据库日期。 I cannot use Java to pass any parameter into the query.我不能使用 Java 将任何参数传递到查询中。

My customer Entity looks like this :我的客户实体如下所示:

@Entity
@Table(name = "customer")
public class Customer {

   @Id
   @Column(name = "cust_no")
   private int custNo;

   @Temporal(TemporalType.TIMESTAMP)
   @Column(name = "registration_timestamp")
   private Date registrationTimeStamp;
}

And my customer repository will be like:我的客户存储库将如下所示:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

   @Query(value = "SELECT c FROM Customer c WHERE c.registrationTimeStamp <= SOMETHING")
   List<Customer> getCustomers24HoursAfterRegistration();

}

I really don't know what should I put that place refers SOMETHING.我真的不知道我应该放什么那个地方指的是某些东西。 I think I can use something like CURRENT_TIMESTAMP - SOMETHING_REFERS_24_HOURS.我想我可以使用像 CURRENT_TIMESTAMP - SOMETHING_REFERS_24_HOURS 这样的东西。 All the examples are about the nativeQuery.所有的例子都是关于 nativeQuery 的。 Or passing parameter from Java.或者从Java传递参数。 I can't use INTERVAL because Spring JPA doesnt support.我不能使用 INTERVAL 因为 Spring JPA 不支持。

I can not believe that such a simple process is not in Spring JPA which supports both two RDBMS (PostgreSql and H2).我无法相信这样一个简单的过程在支持两个 RDBMS(PostgreSql 和 H2)的 Spring JPA 中没有。 And I want to ask is there any way to do that?我想问一下有没有办法做到这一点?

If you don`t wanna you native query then you have to use Query methods如果您不想使用本机查询,则必须使用 Query 方法

you can do something like你可以做类似的事情

 List<User> findByCreatedAtGreaterThanEqual(Data createdAt);

For more, you can see ( https://www.baeldung.com/spring-data-jpa-query-by-date , https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods )有关更多信息,您可以查看( https://www.baeldung.com/spring-data-jpa-query-by-datehttps://docs.spring.io/spring-data/jpa/docs/current/reference /html/#jpa.query-methods )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM