从使用hibernate复合主键的表中读取数据

时间:2013-07-24 07:52:49

标签: java database hibernate

我的项目中有这些POJO课程。

 public class MerchantChainUser extends com.avanza.ni.common.dto.AbstractDTO
    implements java.io.Serializable {

private long chainId;
private CompositePK compositePK;


public MerchantChainUser() {

}

public void setChainId(long chainId) {
    this.chainId = chainId;
}
public long getChainId() {
    return chainId;
}

public void setCompositePK(CompositePK compositePK) {
    this.compositePK = compositePK;
}

public CompositePK getCompositePK() {
    return compositePK;
}
}

AND    

public class CompositePK implements Serializable {

private long merchantId;
private long userId;

public void setMerchantId(long merchantId) {
    this.merchantId = merchantId;
}

public long getMerchantId() {
    return merchantId;
}

public void setUserId(long userId) {
    this.userId = userId;
}

public long getUserId() {
    return userId;
}
 }

MerchantUserChain的hbm.xml文件是

 <hibernate-mapping>
<class name="com.avanza.ni.portal.dto.MerchantChainUser" table="MERCHANT_CHAIN_USER">
    <composite-id name="compositePK">
        <key-property name="merchantId" type="long" column="MERCHANT_ID"></key-property>
        <key-property name="userId" type="long" column="MERCHANT_USER_ID"></key-property>
    </composite-id>
    <property name="chainId" type="long">
        <column name="MERCHANT_CHAIN_ID" length="38" />
    </property>
</class>

现在我想要的是我必须使用MERCHANT_USER_ID从表中读取数据。我能够从表中检索整个数据,但现在我想将标准设置为Only give me those row that MERCHANT_USER_ID is specific。我不知道如何编写数据标准。

2 个答案:

答案 0 :(得分:2)

我把评论的答案删除了,所以我在这里发布:D

Criteria crit = session.createCriteria(MerchantChainUser.class)
.add(Restrictions.eq("compositePK.userId", userId));

或使用hql

session.createQuery("from MerchantChainUser where compositePK.userId = :userid").setParameter("userid",userid);

答案 1 :(得分:0)

你可以尝试:

Criteria crit = session.createCriteria(MerchantChainUser.class);
crit.add(Restrictions.eq("compositePK.merchantId", 42));
crit.add(Restrictions.eq("compositePK.userId", 43));
crit.setMaxResults(10);
List result = crit.list();

摄影指导Vinit