JPA Spring - 使用字符串过滤

问题描述 投票:0回答:2

我有人,我只想得到以某个字母开头的字母(字母来自输入字段)。没有查询可以得到这个吗?我怎样才能做到这一点?

@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 = "firstname" ,required=false) String insnr) throws ParseException {         
       mysearch.setFirstname(firstname); 
       return personService.all(mysearch).collect(Collectors.toList()); 
   } 
java spring filter spring-data-jpa
2个回答
1
投票

你的意思是 :

String start = "";
return personRepository.findAll().stream()
              .filter(person -> person.getName().startsWith(start)) //<<---Note this
              .map(Person::fromPerson); 

或者,如果您有不敏感的案例,您可以使用:

String start = "";
return personRepository.findAll().stream()
              .filter(person -> 
                      person.getName().matches("(?i)^" + Pattern.quote(input) + ".*"))//(1)
              .map(Person::fromPerson); 

(1)对于不敏感的情况,例如,如果你的记录是“你好”并且输入是“他”它将被选中,除了匹配使用正则表达式,所以你的正则表达式应该看起来像"(?i)he.*"


0
投票

假设您要使用名字或姓氏进行过滤

public List<Person> findByFirstNameLike(String firstName); // filter with firstname

public List<Person> findByLastNameLike(String lastName); // filter with lastname

要么

public List<Person> findByFirstNameOrLastNameLike(String searchKey); // return list of Persons that firstname or lastname like the searchKey specified 
© www.soinside.com 2019 - 2024. All rights reserved.