[英]Dynamic amount of parameters in where clause
一開始,我需要說的是,我嘗試這樣做的方式可能很愚蠢,但這只是我自己弄清楚的一種方式。
我有帶有汽車屬性的表,有一次我需要通過一個參數獲取日期{“ mark”:“ Audi”}
其他時間我需要更具體的{“ mark”:“ Audi”,“ model”:“ 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返回WHERE子句“ mark = Audi&model = A4”,然后我嘗試將這部分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']
但是此請求始終返回空集合,如果我直接在DB上使用select * from Vehicle where mark ='Audi'&model ='A4'從我得到正確的結果。
你知道為什么嗎?
您不能使用准備好的語句來“注入”整個where子句,因為它會轉義您的“本地字符串”,因此最終
SELECT * FROM whatever WHERE '123456'
或類似的東西。
對於動態條件(您的情況),請使用CriteriaAPI
因此CriteriaBuilder
將成為您的朋友。
建議在SQL方面使用COALESCE 。
不確定是否可以在春季使用
在您的情況下,它可以像這樣工作:
SELECT * FROM Vehicle WHERE COALESCE(mark = :mark, true) and COALESCE(model = :model, true) and COALESCE(engine_power = :engine_power, true) and COALESCE(seat_count = :seat_count, true) and COALESCE(doors_count = :doors_count, true) and COALESCE(gearbox_count = :gearbox_count, true) and COALESCE(type = :type, true) ;
這建議您將所有可能的參數放在“和COALESCE(attribute =:attribute,true)”或“和COALESCE(attribute =?1,true)”之間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.