Check date between two other dates spring data jpa

牧云@^-^@ 提交于 2019-11-27 11:56:00

问题


I have this model:

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

and repository as

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

What I want to do is, I will pass one date and need to check that date is between start and end eg(i will pass sept 30 as date and need to find all entries which have sept 30 between their start and end)

Something like findDateisBetweenStartAndEnd(Date date)?


回答1:


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.




回答2:


I did use following solution to this:

findAllByStartDateLessThanEqualAndEndDateGreaterThanEqual(OffsetDateTime endDate, OffsetDateTime startDate);



回答3:


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);


来源:https://stackoverflow.com/questions/39784344/check-date-between-two-other-dates-spring-data-jpa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!