Spring boot JPA findBy查询创建加自定义参数

Spring boot JPA findBy查询创建加自定义参数,spring-boot,hibernate,jpa,spring-data-jpa,repository,Spring Boot,Hibernate,Jpa,Spring Data Jpa,Repository,我将springboot2.2.6与JPA和postgresqldbms一起使用 假设我有实体国家,如下所示: @Entity @Data @Table(name = "nation") public class Nazione { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String nome; private Boolea

我将
springboot2.2.6
JPA
postgresqldbms
一起使用

假设我有
实体
国家,如下所示:

@Entity
@Data
@Table(name = "nation")
public class Nazione {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;

  private String nome;
  private Boolean active;
}
我有
存储库

@Repository
public interface NazioneRepository extends JpaRepository<Nazione, Integer> {
  public List<Nazione> findByActiveTrue();
}
有了这个,我想检索所有国家
活动
设置为
true
nome
等于作为参数传递的字符串(我测试了它,但不起作用)

也许在这种情况下,我可以这样做:

public List<Nazione> findByActiveTrueAndNome(String nome);
公共列表findByActiveTrueAndNome(字符串nome);
但我要问的是更复杂的情况。我能以某种方式做到这一点吗

谢谢大家

试试看

public List<Nazione> findByActiveTrueAndNomeEquals(String nome);

公共列表findByActiveTrueAndNomeEquals(字符串nome);
或者如果您想要更多的“本机查询”:

@Query("select n from Nazione n where n.nome = ?1 and active=true")
  public List<Nazione> findByActiveTrue(String nome);
@Query(“从Nazione n中选择n,其中n.nome=?1,active=true”)
公共列表findByActiveTrue(字符串nome);
您不能将@Query与auto混合使用

有时我会使用jpa规范(用于具有许多过滤器的端点。例如:

public class NazioneSpec {

    private String nome;

    public Specification<SalesInvoice> getSpecification() {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            query.distinct(true);

            if (nome != null) {
                predicates.add(cb.equal(root.get(Nazione_.nome), nome));
            }
            predicates.add(cb.equal(root.get(Nazione_.active), true));

            return cb.and(predicates.toArray(new Predicate[0]));
        };
    }
}
公共类规范{
私有字符串名称;
公共规范getSpecification(){
返回(根、查询、cb)->{
列表谓词=新的ArrayList();
query.distinct(true);
如果(nome!=null){
add(cb.equal(root.get(Nazione_.nome),nome));
}
add(cb.equal(root.get(Nazione_.active),true));
返回cb.and(谓词toArray(新谓词[0]);
};
}
}
然后,你可以使用:

    @GetMapping(value = "/nazioneList")
    public List<Nazione> getList(NazioneSpec spec) {
       return repository.findAll(spec.getSpecification());
    }
@GetMapping(value=“/nazioneList”)
公共列表getList(NazioneSpec规范){
返回repository.findAll(spec.getSpecification());
}

谢谢你,伙计!我想@Query会覆盖JPA创建的wich-one。。。
    @GetMapping(value = "/nazioneList")
    public List<Nazione> getList(NazioneSpec spec) {
       return repository.findAll(spec.getSpecification());
    }