[英]Java Spring hibernate HQL where clause not working
我有一個帶有 JOIN 的 HQL 查詢,但連接實體上的 where 子句 (instrPrice.date BETWEEN :dateFrom AND :dateTo ) 不起作用。 查詢始終返回 instrumentPrice 的所有記錄,而不是按日期限制結果。
命名查詢
@NamedQuery(name = "findAllPrices",
query = "SELECT DISTINCT taPat FROM TaPatternInstrument taPat "
+ "LEFT JOIN FETCH taPat.instrument instr "
+ "LEFT JOIN instr.instrumentPriceList instrPrice "
+ "WHERE taPat.id = :taPatternInstrumentId "
+ "AND instrPrice.date BETWEEN :dateFrom AND :dateTo ")
調用查詢的服務
public TaPatternInstrument findAllPrices(int taPatternInstrumentId, LocalDate dateFrom, LocalDate dateTo) {
TypedQuery<TaPatternInstrument> typedQuery = createNamedQuery("findAllPrices",
TaPatternInstrument.class);
typedQuery.setParameter("taPatternInstrumentId", taPatternInstrumentId);
typedQuery.setParameter("dateFrom", dateFrom);
typedQuery.setParameter("dateTo", dateTo);
return typedQuery.getSingleResult();
}
實體
public abstract class BaseEntity implements Serializable {
@Id
@Column(name = "id")
@GeneratedValue(strategy =
GenerationType.IDENTITY)
protected int id; ...
}
public class TaPatternInstrument extends BaseEntity {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "instrument_id", nullable = false, foreignKey = @ForeignKey(name =
"tapatterninstrument_instrument_fk"))
private Instrument instrument;
}
public class Instrument extends BaseEntity {
@OneToMany(mappedBy = "instrument", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<InstrumentPrice> instrumentPriceList;
}
SELECT DISTINCT tapatterni0_.id AS id1_34_0_,
...
FROM tapatterninstrument tapatterni0_
LEFT OUTER JOIN instrument instrument1_
ON tapatterni0_.instrument_id = instrument1_.id
LEFT OUTER JOIN instrumentprice instrument2_
ON instrument1_.id = instrument2_.instrument_id
WHERE tapatterni0_.id = ?
AND ( instrument2_.date BETWEEN ? AND ? )
解決方案是在 instrumentPriceList 上添加一個 FETCH : LEFT JOIN FETCH instr.instrumentPriceList instrPrice
@NamedQuery(name = "findAllPrices",
query = "SELECT DISTINCT taPat FROM TaPatternInstrument taPat "
+ "LEFT JOIN FETCH taPat.instrument instr "
+ "LEFT JOIN FETCH instr.instrumentPriceList instrPrice "
+ "LEFT JOIN taPat.taPatternInstrumentPriceList taPatpr "
+ "WHERE taPat.id = :taPatternInstrumentId "
+ "AND instrPrice.date BETWEEN :dateFrom AND :dateTo ")
FETCH 強制 Hibernate 在第一個 DB 請求時立即檢索實體 (InstrumentPrice)。 因此考慮了 where 子句。 如果沒有 FETCH,則只有在調用實體工具的方法 getInstrumentPriceList 時才從數據庫中檢索實體工具價格(執行對數據庫的額外調用)。 並且通過對數據庫的這個額外調用,不再考慮 where 子句,從而從實體 instrumentPrice 檢索所有記錄。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.