Spring启动动态查询

Fel*_* A. 10 java spring-boot

我的webapp中有一个过滤器,允许按车辆类型,品牌,燃料,州和城市搜索,但所有这些过滤器都是可选的.

如何使用存储库执行此操作.

控制器类

@RequestMapping(value = "/vehicle/search", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<Veiculo> findBySearch(@RequestParam Long vehicletype, @RequestParam Long brand, 
        @RequestParam Long model, @RequestParam Long year, 
        @RequestParam Long state, @RequestParam Long city) {
    return veiculoService.findBySearch(vehicletype, brand, model, year, state, city);
}
Run Code Online (Sandbox Code Playgroud)

服务类

public Iterable<Vehicle> findBySearch(Long vehicletype, Long brand, Long model, Long year, Long state, Long city) {
    if(vehicletype != null){
        //TODO: filter by vehicletype
    }
    if(brand != null){
        //TODO: filter by brand
    }
    if(model != null){
        //TODO: filter by model
    }

    //OTHER FILTERS
    return //TODO: Return my repository with personal query based on filter
}
Run Code Online (Sandbox Code Playgroud)

我还没有实现任何东西,因为我不明白我该怎么做这个过滤器.

车辆类

@Entity
@Table(name = "tb_veiculo")
public class Veiculo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long id;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "veiculo_opcionais", 
    joinColumns = @JoinColumn(name = "veiculo_id", referencedColumnName = "id"),
    inverseJoinColumns = @JoinColumn(name = "opcional_id", referencedColumnName = "id"))
    private List<Opcional> opcionais;

    @JsonIgnore
    @OneToMany(mappedBy = "veiculo", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<VeiculoImagem> veiculoImagens;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "cambio_id", foreignKey = @ForeignKey(name = "fk_cambio"))
    private Cambio cambio;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "combustivel_id", foreignKey = @ForeignKey(name = "fk_combustivel"))
    private Combustivel combustivel;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "cor_id", foreignKey = @ForeignKey(name = "fk_cor"))
    private Cor cor;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "modelo_id", foreignKey = @ForeignKey(name = "fk_modelo"))
    private Modelo modelo;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "usuario_id", foreignKey = @ForeignKey(name = "fk_usuario"))
    private Usuario usuario;

    @Column(name = "anoFabricacao", nullable = false)
    private int anoFabricacao;

    @Column(name = "anoModelo", nullable = false)
    private int anoModelo;

    @Column(name = "quilometragem", nullable = false)
    private int quilometragem;

    @Column(name = "porta", nullable = false)
    private int porta;

    @Column(name = "valor", nullable = false)
    private double valor;

    //GETTERS AND SETTERS
Run Code Online (Sandbox Code Playgroud)

车型和品牌来自另一张桌子......我是葡萄牙语,我把代码翻译成英文...

当它发生时,我需要做什么?

g00*_*00b 10

您可以使用Spring中的规范API,它是JPA标准API的包装器,允许您创建更多动态查询.

你的情况我假设你有一个Vehicle,有一个领域的实体brand,year,state,city,....

如果是这种情况,您可以编写以下规范:

public class VehicleSpecifications {
    public static Specification<Vehicle> withCity(Long city) {
        if (city == null) {
            return null;
        } else {
            // Specification using Java 8 lambdas
            return (root, query, cb) -> cb.equal(root.get("city"), city);
        }
    }

    // TODO: Implement withModel, withVehicleType, withBrand, ...
}
Run Code Online (Sandbox Code Playgroud)

如果你必须进行连接(例如,如果你想要检索Vehicle.city.id),那么你可以使用:

return (root, query, cb) -> cb.equal(root.join("city").get("id"), city);
Run Code Online (Sandbox Code Playgroud)

现在,在您的存储库中,您必须确保从中扩展JpaSpecificationExecutor,例如:

public interface VehicleRepository extends JpaRepository<Vehicle, Long>, JpaSpecificationExecutor<Vehicle> {

}
Run Code Online (Sandbox Code Playgroud)

通过从此界面扩展,您将可以访问findAll(Specification spec)允许您执行规范的方法.如果您需要组合多个规范(通常一个过滤器=一个规范),您可以使用以下Specifications类:

repository.findAll(where(withCity(city))
    .and(withBrand(brand))
    .and(withModel(model))
    .and(withVehicleType(type))
    .and(withYear(year))
    .and(withState(state)));
Run Code Online (Sandbox Code Playgroud)

在上面的代码示例中,我使用静态导入,Specifications.whereVehicleSpecifications.*使其看起来更具说明性.

你不必if()在这里写句子,因为我们已经写过了VehicleSpecifications.withCity().只要你null从这些方法返回,它们将被Spring忽略.