检查其他两个日期之间的日期

我有个模型:

public class Event {
private String name;
private Date start;
private Date end;
}

以及储存库作为

@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
List<Event> findByEventTypeAccount(Account account);
}

我想做的是,我将通过一个日期,并需要检查日期之间的 startend例如(我将通过9月30日作为日期,并需要找到所有条目之间的 startend之间的9月30日)

findDateisBetweenStartAndEnd(Date date)之类的?

265152 次浏览

You should take a look the reference documentation. It's well explained.

In your case, I think you cannot use between because you need to pass two parameters

Between - findByStartDateBetween … where x.startDate between ?1 and ?2

In your case take a look to use a combination of LessThan or LessThanEqual with GreaterThan or GreaterThanEqual

  • LessThan/LessThanEqual

LessThan - findByEndLessThan … where x.start< ?1

LessThanEqual findByEndLessThanEqual … where x.start <= ?1

  • GreaterThan/GreaterThanEqual

GreaterThan - findByStartGreaterThan … where x.end> ?1

GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1

You can use the operator And and Or to combine both.

I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);

You can also write a custom query using @Query

@Query(value = "from EntityClassTable t where yourDate BETWEEN :startDate AND :endDate")
public List<EntityClassTable> getAllBetweenDates(@Param("startDate")Date startDate,@Param("endDate")Date endDate);

Edit: For LocalDateTime I just tried this solution for filtering record based on date and type in spring JPA:

Page<MyEntity> findMyEntityByEntityDateBetweenAndType(
@Param("startDate") LocalDateTime startDate,
@Param("endDate") LocalDateTime endDate, @Param("type") String type, Pageable pageable);

Here EntityDate can be like CreatedDate,ModifiedDate etc.

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

https://www.baeldung.com/spring-data-jpa-query-by-date

You can use JpaRepository

List<Entity> findByColumnDateBetween(LocalDateTime to, LocalDateTime from);