【问题标题】:Filter Data with Spring JPA Query使用 Spring JPA 查询过滤数据
【发布时间】:2018-06-27 06:39:27
【问题描述】:

我有 Persons,我只想获取以某个字母开头的那些(该字母来自输入字段)。我有查询,但我不能“使用”它。 我怎样才能做到这一点?

存储库:

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

【问题讨论】:

  • 你不能用是什么意思
  • 我收到错误“Stream 类型的方法 stream() 未定义”。
  • 我发现我的错误,应该多想一点。必须将 Stream 更改为 List @Query("From Person where firstname like CONCAT(:firstname,'%')") **Stream** findAllWithSearchParams(@Param("firstname") String firstname);跨度>
  • 这是:findByFirstnameStartingWith(String firstname)?

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


【解决方案1】:

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

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

    List<Person> findByFirstnameStartingWith(String firstname);

}

【讨论】:

    猜你喜欢
    • 2012-05-04
    • 2021-02-17
    • 2013-12-15
    • 1970-01-01
    • 2020-01-25
    • 2015-03-26
    • 2013-12-13
    • 2018-02-22
    相关资源
    最近更新 更多