我的网络应用程序中有一个过滤器,允许按车辆类型,品牌,燃料,州和城市搜索,但所有这些过滤器都是可选的。
如何使用存储库执行此操作。
控制器类
@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
它的车型和品牌来自另一张桌子...我是葡萄牙语,我把代码翻译成英文......
什么时候发生,我需要做什么?
答案 0 :(得分:8)
您可以使用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, ...
}
如果您必须进行加入(例如,如果您想要检索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就会忽略它们。