[英]Spring boot Dynamic Query
我的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);
}
服务类
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
}
我还没有实现任何东西,因为我不明白我该怎么做这个过滤器。
车辆类
@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
车型和品牌来自另一张桌子......我是葡萄牙语,我把代码翻译成英文...
当它发生时,我需要做什么?
您可以使用Spring中的规范API,它是JPA标准API的包装器,允许您创建更多动态查询。
在您的情况下,我假设您有一个拥有现场brand
, year
, state
, city
......的Vehicle
实体。
如果是这种情况,您可以编写以下规范:
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, ...
}
如果你必须进行连接(例如,如果你想检索Vehicle.city.id
),那么你可以使用:
return (root, query, cb) -> cb.equal(root.join("city").get("id"), city);
现在,在您的存储库中,您必须确保从JpaSpecificationExecutor
扩展,例如:
public interface VehicleRepository extends JpaRepository<Vehicle, Long>, JpaSpecificationExecutor<Vehicle> {
}
通过从此接口扩展,您将可以访问允许您执行规范的findAll(Specification spec)
方法。 如果您需要组合多个规范(通常一个过滤器=一个规范),您可以使用Specifications
类:
repository.findAll(where(withCity(city))
.and(withBrand(brand))
.and(withModel(model))
.and(withVehicleType(type))
.and(withYear(year))
.and(withState(state)));
在上面的代码示例我使用静态导入Specifications.where
和VehicleSpecifications.*
让它看起来更具声明一点。
您不必在此处编写if()
语句,因为我们已经在VehicleSpecifications.withCity()
编写了它们。 只要从这些方法返回null
,Spring就会忽略它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.