Powered By Blogger

Sunday, December 11, 2011

Detached Criteria - Hibernate

The following is an example usage of DetachedCriteria in hibernate. CoinTrxLedger is the domain class which is to be queried and it consists of a set of CoinBuckets. Detached Criteria is used to prepare a sub-query using CoinBuckets (which is not the main query class).
CoinTrxLedger entities are to be selected, which are having CoinBucket entities having the CoinBucket.PROPERTY_ACCOUNT set to An entity, account (passed in to the method).

===================================================================

    public List<CoinTrxLedger> getTransactionEntries(Account account) {
        Session session = getSessionFactory().getCurrentSession();
        Criteria criteria = session.createCriteria(CoinTrxLedger.class);
        DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
        dCriteria.add(Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
        dCriteria.setProjection(Projections.property(CoinBucket.PROPERTY_ID));
        criteria.add(Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));
        return criteria.list();
    }

===================================================================

Create a criteria of the query entity;
          Criteria criteria = session.createCriteria(CoinTrxLedger.class);

Create the sub-query, define restrictions and projections as required:
         DetachedCriteria dCriteria = DetachedCriteria.forClass(CoinBucket.class);
     dCriteria.add(

Restrictions.eq(CoinBucket.PROPERTY_ACCOUNT, account));
     dCriteria.setProjection(Projections

.property(CoinBucket.PROPERTY_ID));

Add the sub-query to the main criteria:
        criteria.add(
Subqueries.propertyEq(CoinTrxLedger.PROPERTY_COIN_BUCKET, dCriteria));

thanks,
Shyarmal

No comments:

Post a Comment