gpt4 book ai didi

java - where 子句中参数的动态数量

转载 作者:行者123 更新时间:2023-12-02 10:39:15 24 4
gpt4 key购买 nike

一开始我需要说,我尝试这样做的方式可能很愚蠢,但这只是我想出来的一种方式。

我有一个包含汽车属性的表,有一次我需要通过一个参数获取日期{ “马克”:“奥迪”}

其他时候我需要更具体的信息{ “标记”:“奥迪”, “型号”:“A4”}

所以我写方法

    public List<Object> findVehicleProperty(String propertyType, Vehicle vehicle) {
String queryParam = "";

if(vehicle.getMark() != null) queryParam += "mark='"+vehicle.getMark()+"'&";
if(vehicle.getModel() != null) queryParam += "model='"+vehicle.getModel()+"'&";
if(vehicle.getEnginePower() != null) queryParam += "engine_power="+vehicle.getEnginePower()+"&";
if(vehicle.getSeatCount() != null) queryParam += "seat_count="+vehicle.getSeatCount()+"&";
if(vehicle.getDoorsCount() != null) queryParam += "doors_count="+vehicle.getDoorsCount()+"&";
if(vehicle.getGearboxCount() != null) queryParam += "gearbox_count="+vehicle.getGearboxCount()+"&";
if(vehicle.getType() != null) queryParam += "type="+vehicle.getType()+"&";


//remove last "&" mark
if (queryParam.length() > 0) {
queryParam = queryParam.substring(0, queryParam.length() - 1);
}


return vehicleRepository.getParameters(queryParam);
}

它从sql“mark=Audi&model=A4返回WHERE子句,然后我尝试将这部分sql作为参数传递到存储库

@Query(value = "select * from Vehicle where ?1", nativeQuery = true)
List<Object> getParameters(String query);

我安慰我可以看到它的交互性很好

2018-10-29 21:35:57.488 DEBUG 6240 --- [nio-8080-exec-1] org.hibernate.SQL                        : select * from Vehicle where ?

2018-10-29 21:35:57.494 TRACE 6240 --- [nio-8080-exec-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARCHAR] - [mark='Audi'&model='A4']

但是这个请求总是返回空集合,如果我直接在数据库上使用 select * from Vehicle where mark='Audi'&model='A4' ,我会得到正确的结果。

你知道为什么吗?

最佳答案

您不能使用准备好的语句来“注入(inject)”整个 where 子句,因为它会转义您的“ native 字符串”,因此您最终会得到

SELECT * FROM whatever WHERE '123456'

或类似的东西。

对于动态条件(即您的情况),请使用 CriteriaAPI,这样 CriteriaBuilder 将成为您的 friend 。

关于java - where 子句中参数的动态数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053478/

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