在@Formula
annotation只有常見的SQL代碼是允許的。當Hibernate查詢數據庫時,公式將作爲子選擇插入。公式的值中不允許使用HQL或Java代碼。
從Hibernate文檔:
可以使用SQL片段(又名式),而不是映射屬性成一列。
假設我們有一個getter註釋這樣的:
@Formula("(SELECT COUNT(*) from t_child c WHERE c.parent_id = parent_id)")
public int getChildCount() {
return childCount;
}
Hibernate就會產生這個查詢:
SELECT this_.parent_id AS parent1_0_1_,
this_.name_ AS name2_0_1_,
-- Block start
(SELECT COUNT(*)
FROM t_child c
WHERE c.parent_id = this_.parent_id) AS formula0_1_,
-- Block end
tchild1_.parent_id AS parent3_3_,
tchild1_.child_id AS child1_3_,
tchild1_.child_id AS child1_1_0_,
tchild1_.parent_id AS parent3_1_0_,
tchild1_.name_ AS name2_1_0_
FROM test.t_parent this_
LEFT OUTER JOIN test.t_child tchild1_
ON this_.parent_id = tchild1_.parent_id
WHERE this_.parent_id =?
我想強調的是由於創建到@Formula
註釋塊。希望這有助於理解,Hibernate公式如何工作以及公式需要哪種格式。
我可以確認結束'END'是必須的 - 至少對於H2數據庫來說。 – msparer