java - What is the best way to query a JPA entity for instances based on the current date+time? -


I have an entity type with two dates, start and end times:

  Import Org .joda.time.DateTime; @ Antiti public class Thing {@ type ( "type =" org.jadira.usertype.dateandtime.joda.PersistentDateTime ") private Dettaim Startdet: @ type (type =" org.jadira.usertype.dateandtime.joda.PersistentDateTime ") Private Dinanktaim expiry date;}  

I have extended this entity type Spring Data-JPA repositories (for CrudRepository ), and there I all

startDate & lt; = now & lt; = endDate

I said tried to "active", "active" one Jepiupiel query in this way, Lake This is not producing the desired results in some of our tests:

  select @Query ( "Thing T where t.startDate & lt; = CURRENT_TIMESTAMP and t.endDate & Gt; = CURRENT_TIMESTAMP ") public Iterebl & lt; Thing & gt; findAllActive ();  

I also tried a method-name-conference query, which I hope Generates results, but it is weird:

  public interchangeable  FindByStartDateBeforeAndEndDateAfter (DateTime MinuteDrade, DateTime maxEndDate);  

I like my @Service like

  Public Iterbal & lt; Thing & gt; GetActiveThings () {DateTime now = DateTime.now (); Return repository.FindbistStateDate and First EndettEfter (now, now); }  

Then the service interface is clean, but the repo interface is ugly and weird (in my opinion).

Is this a better way of creating a repository query method using JPA, either a better method-name-based query or a clear JPQL query? I would not want to create a query object manually in the code (I do not even have a solid square for the repository, only one interface), but if I believe this is the best way.

You can just have the following:

  @Query (" Select t that t from where t.startDate & lt; =: time and t.endDate> =: time ") public irrelevant & lt; Thing & gt; Search Active Content (@Param ("Time") Date Time);  

Has the advantage of using only 1 parameter, but you also get permission to inquire later such as: "Give me a list of active things on January 24, 2011"


Comments