Waqas Ali
Waqas Ali

Reputation: 1652

Read data from table where primary key is composite using hibernate

I have these POJO classes in my project.

 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;
}
 }

hbm.xml file for MerchantUserChain is

 <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>

Now what i wanted is i have to read data from the table using just MERCHANT_USER_ID. I am able to retreive whole data from the table but now i want to set a criteria as Only give me those row that MERCHANT_USER_ID is specific. I didn't know how to write data criteria.

Upvotes: 1

Views: 1758

Answers (2)

Angga
Angga

Reputation: 2323

the answer that i put the comment has been deleted, so i post it here :D

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

or with hql

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

Upvotes: 2

Vinit Prajapati
Vinit Prajapati

Reputation: 1613

Can you try:

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

Upvotes: 0

Related Questions