@Formula
注釈では、一般的な SQL コードのみが許可されます。Hibernate がデータベースにクエリを実行すると、式が副選択として挿入されます。式の値に HQL または Java コードを使用することはできません。
Hibernate のドキュメントから:
プロパティを列にマッピングする代わりに、SQL フラグメント (式) を使用できます。
次のような注釈が付けられたゲッターがあると仮定します。
@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 数式がどのように機能するか、および数式に期待される形式を理解するのに役立つことを願っています。