复合PK字段的分离标准?

时间:2011-09-07 11:03:19

标签: java hibernate hibernate-criteria detachedcriteria

我有一个包含3列作为主键的表。代码和映射如下:

复合键的类

public class CIDResultCurrentState implements Serializable
{
    private static final long serialVersionUID = -4346801004559840730L;

    private String mID = "";
    private String sNo = "";
    private String date = "";
    // getters, setters, equals(), hashCode() omitted for brevity 
}

表的类

public class ResultCurrentState implements IBaseModel, Serializable
{
    private static final long serialVersionUID = 5707101766665188676L;

    private CIDResultCurrentState ID;
    private byte[] rData;
    private byte[] pData;
    // getters, setters, equals(), hashCode() omitted for brevity 
}

hibernate xml map

<hibernate-mapping>

<class name="org.irvas.amrregina.backend.model.ResultCurrentState" table="RESULT_CURRENT_STATE">

    <composite-id name="ID" class="org.irvas.amrregina.backend.model.CIDResultCurrentState">
        <key-property name="mID" column="M_ID" type="java.lang.String"/>
        <key-property name="sNo" column="S_NO" type="java.lang.String"/>
        <key-property name="date" column="S_DATE" type="java.lang.String"/>
    </composite-id>

    <property name="rData" column="R_DATA" not-null="false" type="binary"/>
    <property name="pData" column="P_DATA" not-null="false" type="binary"/>

</class>

</hibernate-mapping>

所有这一切都很好。现在,我需要编写DetachedCriteria查询以获取特定的ResultCurrentState对象/记录。我试过这样的东西,但它不起作用(我不知道是否将此复合ID视为嵌套属性):

//...
DetachedCriteria criteria = DetachedCriteria.forClass(ResultCurrentState.class);
DetachedCriteria criteriaID = criteria.createCriteria("ID");
criteriaID.add(Restrictions.eq("mID", arg.getType().getMID()));
criteriaID.add(Restrictions.eq("sNo", arg.getSN()));
criteriaID.add(Restrictions.eq("date", date));
return (ResultCurrentState)DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteriaID));

如果有人可以帮我写出正确的标准,我真的很感激 感谢。

2 个答案:

答案 0 :(得分:2)

对于使用复合主键的标准,这应该足够了:

DetachedCriteria criteria = DetachedCriteria.forClass(ResultCurrentState.class);
criteria.add(Restrictions.eq("ID.mID", arg.getType().getMID()));
criteria.add(Restrictions.eq("ID.sNo", arg.getSN()));
criteria.add(Restrictions.eq("ID.date", date));

请注意,ID用作前缀,因为您已在类ResultCurrentState中使用该名称在POJO中声明了复合键:

private CIDResultCurrentState ID;

至于查询执行,我认为它是这样的(我的不同 - 不一定更好):

return (ResultCurrentState)DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(criteria));

使用我的看起来像这样:

List<ResultCurrentState> result = DataAccessUtils.find(criteria);

答案 1 :(得分:1)

Criteria criteria = session.forClass(ResultCurrentState.class);
DetachedCriteria criteriaID = DetachedCriteria.forClass(CIDResultCurrentState.class);
criteriaID.add(Restrictions.eq("mID", arg.getType().getMID()));
criteriaID.add(Restrictions.eq("sNo", arg.getSN()));
criteriaID.add(Restrictions.eq("date", date));
criteria.add(Subqueries.propertyIn("ID", criteriaID));
return criteria.list();