繁体   English   中英

使用Spring JPA查询过滤数据

[英]Filter Data with Spring JPA Query

我有个人,我只想以某个字母开头(字母来自输入字段)。 我有查询,但是我不能“使用”它。 我如何才能做到这一点?

仓库:

@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()); 
   } 

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

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

    List<Person> findByFirstnameStartingWith(String firstname);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM