JPA Spring - 过滤日期

时间:2017-12-22 09:02:20

标签: java spring spring-data-jpa autowired

是否可以过滤日期?例如,我只想选择过去30天的数据? 选择应该是从现在到现在 - 30天。 我会在没有查询的情况下优先考虑解决方案。

@Service 
public class PersonService { 

   @Autowired 
   private PersonRepository personRepository;         
   public Stream<Person> all(Person mysearch){ 
       return personRepository 
              .findAll(Example.of(mysearch)) 
              .stream() 
              .map(Person::fromPerson); 
  } 
}

班主任:

public class Person { 

    public Integer index; 
    public String firstname; 
    public String lastname; 
    @JsonFormat(pattern="dd.MM.yyyy") 
    public Date exdate; 
    public String insnr; 

    private Person(Integer index, String firstname, String lastname, Date exdate, String insnr){ 
        this.index=index; 
        this.firstname=firstname; 
        this.lastname=lastname; 
        this.exdate=exdate; 
        this.insnr=insnr; 
    } 

    public static Person fromPerson(Person person){ 
        return person == null ? null : new Person(person.getIndex(), person.getFirstname(), person.getLastname(), person.getExdate(), person.getInsnr()); 
    } 
} 

控制器:

@Autowired 
   private PersonService personService; 
   @RequestMapping(value="/person/list/**") 
   public List<Person> loadPersonList(   
                   @RequestParam(value = "insnr" ,required=false) String insnr) throws ParseException {         
       mysearch.setInsnr(insnr); 
       return personService.all(mysearch).collect(Collectors.toList()); 
   } 

2 个答案:

答案 0 :(得分:2)

Spring JPA存储库支持 GreaterThan 关键字queries

您可以考虑以下内容:

LocalDate dateBefore30Days = LocalDate.now().minusDays(30);

List<Person> persons =  personRepository.findByExdateGreaterThan(dateBefore30Days);

答案 1 :(得分:0)

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();    
 public Stream<Person> all(Person mysearch){ 
       return personRepository 
              .findAll(Example.of(mysearch)).stream().filter(person -> person.getExdate().compareTo(dateBefore30Days) > 0)
                .map(Person::fromPerson)                       
                .findAny()
                .orElse(""); }