Hibernate在子句中高级

时间:2012-12-20 16:11:14

标签: java hibernate

我需要在带有hibernate的DB_TABLE上执行SQL查询。 in子句包含值对。我让它在组件映射的帮助下查询(tid,mid)对,见下文。

我现在需要另外为另一对示例(tid,organization)执行in子句查询。我该怎么做?

目标SQL查询

select * from DB_TABLE where ( c_tid, c_mid ) in ( ('t1', 'm1'), etc. )

Java查询代码

function List<DBTable> getDBTableList( List<TidMidId> tidMidList ) {
  Criterion crit = Restrictions.in( "tidMidId", tidMidList.toArray() );
  // pom is hibernate wrapper
  return pom.getObjects( DBTable.class, crit );
}

Hibernate Mapping:

<class name="com.DBTable" table="DB_TABLE" >
    <id name="id" type="long" column="K_ID">
        <generator class="sequence">
            <param name="sequence">DB_TABLE$SEQ</param>
        </generator>
    </id>

    <component name="tidMidId" class="com.TidMidId">
        <property name="tid" type="string" column="C_TID"/>
        <property name="mid" type="string" column="C_MID"/>
    </component>
    <property name="organisation" type="string" column="C_ORGANISATION"/>
    <property name="createTimestamp" type="timestamp" column="D_CREATE_TIMESTAMP"/>
    <property name="modTimestamp" type="timestamp" column="D_MOD_TIMESTAMP"/>
</class>

1 个答案:

答案 0 :(得分:1)

为什么不使用HQL?让Hibernate处理SQL:

Query q = session.createQuery("FROM com.DBTable x WHERE x.tidMidId.tid = ? AND x.tidMidId.mid = ?");
q.setString(0, "t1");
q.setString(1, "m1");
return (List<com.DBTable>) q.list();

添加更多参数非常简单:

q = ".... AND x.organisation = ?");
q.setString(3, "someOrganization");