使用Spring JPA查询过滤数据

时间:2018-01-18 08:47:03

标签: java spring hibernate spring-data-jpa jpql

我有人,我只想得到以某个字母开头的字母(字母来自输入字段)。我有查询,但我不能'使用'它。 我怎样才能做到这一点?

存储库:

@Repository
public interface PersonRepository extends JpaRepository<Person, Integer>{

    @Query("From Person where firstname like CONCAT(:firstname,'%')")
    Stream<Person> findAllWithSearchParams(@Param("firstname") String firstname);


}

服务:

@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 firstname) throws ParseException {         
       mysearch.setFirstname(firstname); 
       return personService.all(mysearch).collect(Collectors.toList()); 
   } 

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要一个查找以某个字母或单词开头的人的查询。所以,你只需要:

@Repository
public interface PersonRepository extends CrudRepository<Person, Integer> {

    List<Person> findByFirstnameStartingWith(String firstname);

}