3

この質問によく似た質問があります。

table2 の field3 と field4 の一致するすべての一意の組み合わせについて、table1 からすべてのデータを選択しています。

これが私の簡素化されたSQLです。

select *
from table1 as t1
where (t1.field1, t1.field2) in (select distinct field3, field4
                                 from table2 as t2
                                 where t2.id=12345);

SQL を Hibernate Criteria に変換する必要があります。エンティティ オブジェクトをテーブルに正しくマッピングし、応答を正しい結果エンティティに変換しますが、where 句を正しく変換できません。

私が持っているもの

Criteria criteria = getSession().createCriteria(Table1.class);

DetachedCriteria subquery = DetachedCriteria.forClass(Table2.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("field3"), "field3");
projectionList.add(Projections.property("field4"), "field4");
subquery.setProjection(Projections.distinct(projectionList));
subquery.add(Restrictions.eq("id", 12345));

where句を次のようにしたい:

criteria.add(Subqueries.in("field1, field2", subquery));

しかし、それは Hibernate では許可されていません。

where 句をロールアウトして 2 つのサブクエリを作成し、結果に対して field1 と field2 の両方をチェックしようとしましたが、サブクエリは常に複数の列を返す必要があるようです。group by を使用してこれを行いましたが、Hibernate は group by の列を射影リストに自動的に追加し、それらを削除する方法が見つかりません。

以下は、group by を使用した同じクエリです。

select *
from table1 as t1
where t1.field1 in (select field3
                    from table2 as t2
                    where t2.id=12345
                    group by field3, field4)
  and t1.field2 in (select field4
                    from table2 as t2
                    where t2.id=12345
                    group by field3, field4);

Hibernate Criteria を使用して where 句を実行することは可能ですか?

Hibernate Criteria を使用できない場合、HQL を使用して where 句を実行できますか?

編集:

@ Larry.Z は、HQL を使用して私の質問に答えます。

Hibernate Criteria で問題を解決できましたが、クエリを次のように変更する必要がありました。

select *
from table1 as t1
where exists (select 1
              table2 as t2
              where t2.id=12345
                and t2.field3=t1.field1
                and t2.field4=t1.field2);

Hibernate 基準に翻訳:

Criteria criteria = getSession().createCriteria(Table1.class, "t1");

DetachedCriteria subquery = DetachedCriteria.forClass(Table2.class, "t2");
subquery.add(Restrictions.eq("t2.id", 12345));
subquery.add(Restrictions.eqProperty("t2.field3", "t1.field1"));
subquery.add(Restrictions.eqProperty("t2.field4", "t1.field2"));
subquery.setProjection(Projections.property("t2.id")); // select the ID rather than 1

元の SQL を使用して Hibernate Criteria を記述できるかどうか、まだ興味があります。

4

2 に答える 2

5

このようなHQLクエリを書いてみてください

String hql = "from Table1 t1 where (t1.field1, t1.field2) in (
    select distinct t2.field3, t2.field4
    from Table2 t2
    where t2.id=12345)";
sessionFactory.getCurrentSession().createQuery(hql).list()
于 2013-11-05T03:14:28.320 に答える
4

Subqueries.propertiesInが必要です。

criteria.add(Subqueries.propertiesIn(
                new String[] { "field1", "field2" },
                detachedCriteria));
于 2014-08-27T10:19:30.593 に答える