【发布时间】:2017-08-14 19:00:39
【问题描述】:
我有一个基于 Hibernate 4.2 和 Spring Boot 1.4 的应用程序。而且我有一个非常具体的 SQL 查询,我无法以高性能的方式使用 HQL 建模。
log.debug("Request to get all current Bids for station : code {}, bidType {}, versionNum {}", code, bidType, grainProAdminProperties.getPrice().getCurrentVersionNumber());
List<Object[]> result = sessionFactory.getCurrentSession().createSQLQuery(
"select bid.*, tp.price as tp_price, tp.price_nds as tp_priceNds " +
"from bid, transportation_price tp, station_location lts, partner part, station stat " +
"where " +
" bid.is_active = true and" +
" bid.archive_date is null and " +
" part.id = bid.elevator_id and " +
" part.station_id = stat.id and " +
" lts.region_id = stat.region_id and " +
" lts.district_id = stat.district_id and " +
" (stat.locality_id is null or " +
" lts.locality_id = stat.locality_id) and " +
" ((cast(tp.station_from_code as text) = lts.code and " +
" cast(tp.station_to_code as text) = cast(:code as text)) " +
" or " +
" (cast(tp.station_to_code as text) = lts.code and " +
" cast(tp.station_from_code as text) = cast(:code as text))) and " +
" cast(bid.bid_type as text) like cast(:bidType as text) and " +
" cast(tp.version_number as int) = cast(:versionNumber as int)").
setResultTransformer(
new ResultTransformer() {
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
log.warn("Transform tuple: {}, aliases {}", tuple, aliases);
return null;
}
@Override
public List transformList(List collection) {
return collection;
}
}
).
setParameter("code", code).
setParameter("versionNumber", grainProAdminProperties.getPrice().getCurrentVersionNumber()).
setParameter("bidType", bidType).
list();
log.debug("Result of request: {}", result);
在日志文件中我可以看到:
Request to get all current Bids for station : code 865065, bidType BUY, versionNum 2
Hibernate: select bid.*, tp.price as tp_price, tp.price_nds as tp_priceNds from bid, transportation_price tp, station_location lts, partner part, station stat where bid.is_active = true and bid.archive_date is null and part.id = bid.elevator_id and part.station_id = stat.id and lts.region_id = stat.region_id and lts.district_id = stat.district_id and (stat.locality_id is null or lts.locality_id = stat.locality_id) and ((cast(tp.station_from_code as text) = lts.code and cast(tp.station_to_code as text) = cast(? as text)) or (cast(tp.station_to_code as text) = lts.code and cast(tp.station_from_code as text) = cast(? as text))) and cast(bid.bid_type as text) like cast(? as text) and cast(tp.version_number as int) = cast(? as int)
Result of request: []
所以返回的结果是空的。我正在尝试使用相同的参数直接在 DB 中执行完全相同的请求,我得到了 3 个结果。
你能预测一下为什么会这样吗?
【问题讨论】:
-
您是否尝试将您的 3 个查询参数硬编码为查询中的常量以检查这不是绑定问题?
-
谢谢@GaëlMarziou!你说的对。我使用 Enum BidType 作为输入参数,我认为标准的 toString() 方法将被调用以在 SQL 中替换。但是买一些理由它不是真的:(你能为我解释一下这种行为的原因吗?
标签: java spring hibernate spring-boot