gpt4 book ai didi

java - Spring Boot 动态查询

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:56:56 25 4
gpt4 key购买 nike

我的网络应用程序中有一个过滤器,允许按车辆类型、品牌、燃料、州和城市进行搜索,但所有这些过滤器都是可选的。

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

Controller 类

@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 的包装器,允许您创建更多动态查询。

在你的例子中,我假设你有一个 Vehicle 实体,它有一个字段 brand, year, state, 城市, ... .

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

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> {

}

通过扩展此接口(interface),您将可以访问 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.whereVehicleSpecifications.* 使用了静态导入,以使其看起来更具声明性。

您不必在这里编写 if() 语句,因为我们已经在 VehicleSpecifications.withCity() 中编写了它们。只要您从这些方法返回 null,它们就会被 Spring 忽略。

关于java - Spring Boot 动态查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39167189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com