Powered By Blogger

Sunday, August 12, 2012

Hibernate Hierarchy Mapping - Table Per Class

This example shows how to map a hierarchy with hibernate using the strategy, table per class. Circle and Square are two classes which extend Shape. The attribute, id of Shape is common to both the subclasses and will be the primary key of the tables created.

===================================================================
// The shape class
package com.shyarmal.hibernate.example.shape;

public class Shape implements IPersistable {

    protected long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}


// Subclass of Shape, Circle
package com.shyarmal.hibernate.example.shape;

public class Circle extends Shape {

    private float radius;
    private float centerX;
    private float centerY;

    public float getRadius() {
        return radius;
    }

    public void setRadius(float radius) {
        this.radius = radius;
    }

    public float getCenterX() {
        return centerX;
    }

    public void setCenterX(float centerX) {
        this.centerX = centerX;
    }

    public float getCenterY() {
        return centerY;
    }

    public void setCenterY(float centerY) {
        this.centerY = centerY;
    }
}


// Subclass of Shape, Square
package com.shyarmal.hibernate.example.shape;

public class Square extends Shape {

    private float length;
    private float topX;
    private float topY;

    public float getTopX() {
        return topX;
    }

    public void setTopX(float topX) {
        this.topX = topX;
    }

    public float getlength() {
        return length;
    }

    public void setlength(float length) {
        this.length = length;
    }

    public float getTopY() {
        return topY;
    }
    public void setTopY(float topY) {
        this.topY = topY;
    }
}

===================================================================
The hibernate xml mapping for the above hierarchy is as follows. All three classes mapping configurations are done in the same hmb file. This configuration will map (and/or create) three tables for the three classes.

===================================================================
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.shyarmal.hibernate.example.shape">
    <class name="Shape" table="SHAPE">
        <id name="id" column="ID" type="long">
            <generator class="native" />
        </id>
        <joined-subclass table="CIRCLE" name="Circle">
            <key column="ID" />
            <property name="radius" column="RADIUS" type="float"/>
            <property name="centerX" column="CENTER_X" type="float"/>
            <property name="centerY" column="CENTER_Y" type="float"/>
        </joined-subclass>
        <joined-subclass table="SQUARE" name="Square">
            <key column="ID" />       
            <property name="length" type="float" column="LENGTH"/>
            <property name="topY" column="TOP_Y" type="float" />
            <property name="topX" column="TOP_X" type="float" />
        </joined-subclass>
    </class>
</hibernate-mapping>

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

As you can notice, the 'class' tag refers to the class, Shape and the primary key is it's id attribute  (mapped with 'generator' tag). Subclasses are mapped with the element, 'joined-subclass', enclosed in 'class' tag. The element, 'key' defines a (foreign key) reference to the 'ID' column of the 'SHAPE' table. Further, the properties specific to each subclass is defined within the 'joined-subclass' element.

thanks,
Shyarmal.

Sunday, July 15, 2012

Scala Mongo Driver Example (hammersmith)

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

package shyarmal.mongo.driver.test.scala

import java.io.InputStream

import org.bson.collection.BSONDocument
import org.bson.io.BasicOutputBuffer
import org.bson.io.OutputBuffer
import org.bson.SerializableBSONObject
import org.bson.BSONSerializer
import org.bson.DefaultBSONDeserializer
import org.bson.DefaultBSONSerializer

import akka.remote.RemoteProtocol.MessageProtocol
import akka.remote.MessageSerializer
import akka.actor.{ActorSystem, ExtendedActorSystem}
import com.typesafe.config.{ConfigFactory, Config}

/**
* Created by IntelliJ IDEA.
* User: danuka
* Date: 6/12/12
* Time: 10:03 AM
* To change this template use File | Settings | File Templates.
*/

class BSONSerializableMessageQueue extends SerializableBSONObject[Message]{
//  var c: Config = ConfigFactory.parseString("akka.extensions = [ \"akka.actor.JavaExtension$TestExtensionId\" ]").withFallback(AkkaSpec.testConf)
  val system : ExtendedActorSystem = ActorSystem.create("JavaExtension", ConfigFactory.load.getConfig("remotelookup")).asInstanceOf[ExtendedActorSystem]
//  val system : ExtendedActorSystem = ActorSystem.create("JavaExtension", null).asInstanceOf[ExtendedActorSystem]
//  val system : ActorSystem = ActorSystem.create()
  protected def serializeDurableMsg(msg: Message)(implicit serializer: BSONSerializer) =  {
   val b = Map.newBuilder[String, Any]
    b += "_id" -> msg._id
    b += "text1" -> msg.text1
    b += "text2" -> msg.text2
    b += "text3" -> msg.text3
    b += "text4" -> msg.text4
    b += "text5" -> msg.text5
    b += "text6" -> msg.text6
    b += "text7" -> msg.text7
    b += "text8" -> msg.text8
    b += "text9" -> msg.text9
    /**
     * TODO - Figure out a way for custom serialization of the message instance
     * TODO - Test if a serializer is registered for the message and if not, use toByteString
     */
//    val msgData = MessageSerializer.serialize(system, msg.text3.asInstanceOf[AnyRef])
//    b += "message" -> new org.bson.types.Binary(0, msgData.toByteArray)
    val doc = b.result
    serializer.putObject(doc)
  }

  /*
   * TODO - Implement some object pooling for the Encoders/decoders
   */
  def encode(msg: Message, out: OutputBuffer) = {
    implicit val serializer = new DefaultBSONSerializer
    serializer.set(out)
    serializeDurableMsg(msg)
    serializer.done
  }

  def encode(msg: Message): Array[Byte] = {
    implicit val serializer = new DefaultBSONSerializer
    val buf = new BasicOutputBuffer
    serializer.set(buf)
    serializeDurableMsg(msg)
    val bytes = buf.toByteArray
    serializer.done
    bytes
  }

  def decode(in: InputStream): Message = {
    val deserializer = new DefaultBSONDeserializer
    // TODO - Skip the whole doc step for performance, fun, and profit! (Needs Salat / custom Deser)
    val doc = deserializer.decodeAndFetch(in).asInstanceOf[BSONDocument]
//    val msgData = MessageProtocol.parseFrom(doc.as[org.bson.types.Binary]("message").getData)
//    val msg = MessageSerializer.deserialize(system, msgData).toString()
    val text1 = doc.as[String]("text1")
    val text2 = doc.as[String]("text2")
    val text3 = doc.as[String]("text3")
    val text4 = doc.as[String]("text4")
    val text5 = doc.as[String]("text5")
    val text6 = doc.as[String]("text6")
    val text7 = doc.as[String]("text7")
    val text8 = doc.as[String]("text8")
    val text9 = doc.as[String]("text9")

    Message(text1, text2, text3, text4, text5, text6, text7, text8, text9)
  }

  def checkObject(msg: Message, isQuery: Boolean = false) = {} // object expected to be OK with this message type.

  def checkKeys(msg: Message) {} // keys expected to be OK with this message type.

  /**
   * Checks for an ID and generates one.
   * Not all implementers will need this, but it gets invoked nonetheless
   * as a signal to BSONDocument, etc implementations to verify an id is there
   * and generate one if needed.
   */
  def checkID(msg: Message) = msg // OID already generated in wrapper message

  def _id(msg: Message): Option[AnyRef] = Some(msg._id)
}


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











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

package shyarmal.mongo.driver.test.scala

import com.mongodb.async.{WriteResult, MongoConnection}
import org.bson.types.ObjectId
import akka.dispatch.Envelope._
import akka.dispatch.Envelope
import akka.actor.{ActorRef, ActorSystem}

/**
  * Created by IntelliJ IDEA.
  * User: danuka
  * Date: 6/11/12
  * Time: 4:26 PM
  * To change this template use File | Settings | File Templates.
  */

case class Message (
                     text1: String,
                     text2: String,
                     text3: String,
                     text4: String,
                     text5: String,
                     text6: String,
                     text7: String,
                     text8: String,
                     text9: String,
                     _id: ObjectId = new ObjectId
                     )  extends BSONSerializableMessageQueue {
  def this() = this("", "", "","", "", "","", "", "")
//  def envelope(system: ActorSystem) = Envelope(text2, text3)(system)
}


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










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

package shyarmal.mongo.driver.test.scala

import com.mongodb.async.futures.RequestFutures
import com.mongodb.async.{WriteResult, MongoConnection}
import akka.AkkaException
import com.mongodb.async._
import com.mongodb.async.futures.RequestFutures
import org.bson.collection._
import akka.config.ConfigurationException
import akka.dispatch._
import akka.util.Duration
import akka.event.{EventStream, Logging}
import akka.remote.MessageSerializer
import akka.actor._
import com.typesafe.config.{ConfigFactory, Config}
import com.mongodb.async.Cursor.Entry
import java.util.concurrent.{ScheduledExecutorService, Executors, TimeUnit, TimeoutException}

/**
  * Created by IntelliJ IDEA.
  * User: danuka
  * Date: 6/11/12
  * Time: 4:26 PM
  * To change this template use File | Settings | File Templates.
  */

class MongoDriverTest {


//  val log = Logging(system, "MongoDriverTest")
  var mongo : Collection = connect()


  private def connect() = {
//    log.info("CONNECTING mongodb uri : [{}]", settings.MongoURI)
    val name : String = "test";
//    val _dbh = MongoConnection.fromURI(settings.MongoURI) match {
    val _dbh = MongoConnection.fromURI("mongodb://localhost:27017/mongoquest") match {
      case (conn, None, None) ⇒ {
        throw new UnsupportedOperationException("You must specify a database name to use with MongoDB; please see the MongoDB Connection URI Spec: 'http://www.mongodb.org/display/DOCS/Connections'")
      }
      case (conn, Some(db), Some(coll)) ⇒ {
//        log.warning("Collection name ({}) specified in MongoURI Config will be used as a prefix for mailbox names", coll.name)
        db("%s.%s".format(coll.name, name))
      }
      case (conn, Some(db), None) ⇒ {
        db("mailbox.%s".format(name))
      }
      case default ⇒ throw new IllegalArgumentException("Illegal or unexpected response from Mongo Connection URI Parser: %s".format(default))
    }
//    log.debug("CONNECTED to mongodb { dbh: '%s | %s'} ".format(_dbh, _dbh.name))
//    println(_dbh.db.name)
//    println(_dbh.name)
//    println(_dbh.writeConcern)
    _dbh
  }

  def main(args: Array[String]) {
    val insertExecutor : ScheduledExecutorService = Executors.newScheduledThreadPool(10)
//    val deleteExecutor : ScheduledExecutorService = Executors.newScheduledThreadPool(2)
//    deleteExecutor.scheduleWithFixedDelay(new Runnable() {
//      def run() {
//        delete();
//      }
//    }, 100, 100, TimeUnit.MILLISECONDS)
    insertExecutor.scheduleWithFixedDelay(new Runnable() {
      def run() {
        try {
          insert();
        } catch {
          case e : Throwable => {
            println(e)
          }
        }
       }
    }, 10, 1, TimeUnit.MILLISECONDS)
  }

  def find() {
    println(mongo.name)
    mongo.find(Document.empty, Document.empty)((cursor: Cursor[Document]) ⇒ {
//        print(cursor.next())
      var x : Entry[Message] = cursor.next.asInstanceOf[Entry[Message]]
      println(" === " + (x.doc != null))
      while (x != null) {
        val document : Document = x.doc.asInstanceOf[Document]
        println("==================")
        println(document.getOrElse("text1", "---"))
        println(document.getOrElse("text2", "---"))
        println(document.getOrElse("text3", "---"))
        println(document.getOrElse("_id", "---"))
        println("==================")
        x = cursor.next.asInstanceOf[Entry[Message]]
       }
    })
  }

  def insert() {
    mongo.insert(new Message("xxc", "dbec", "tuillak", "wec", "7ec", "t89ak", "xqwec", "ddfc", "zxcv"), false)(RequestFutures.write {
      wr: Either[Throwable, (Option[AnyRef], WriteResult)] ⇒
        wr match {
          case Right((oid, wr)) => {println("insert")}
          case Left(t) =>{println("yyyyyyyyyy")}
        }
    }) (mongo.writeConcern, new BSONSerializableMessageQueue())
  }

  def delete() {
    val doc : Document  = Document.empty
    doc.put("text1", "xxc")
    mongo.remove(doc, false) (RequestFutures.write {
      wr: Either[Throwable, (Option[AnyRef], WriteResult)] ⇒
        wr match {
          case Right((oid, wr)) => {println("delete")}
          case Left(t) =>{println("yyyyyyyyyy")}
        }
    })
  }

  def update() {
    println(mongo.name)
//    val q : Document  = Document.empty
//    q.put("text1", "text1")
//    val u : Document  = Document.empty
//    u.put("text1", "tup")
    //Document("text1" -> "upd", "text3" -> "u3", "text2" -> "u2")
    mongo.update(Document("text1" -> "up"), Document("$set" -> Document("text1" -> "upd")), false, true) (RequestFutures.write {
      wr: Either[Throwable, (Option[AnyRef], WriteResult)] =>
        wr match {
          case Right((oid, wr)) => {println("update")}
          case Left(t) =>{println("yyyyyyyyyy")}
        }
    })
  }
}


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



Sunday, June 24, 2012

Quartz 2.0 cron example

This can be considered as an enhancement done to Quartz 2.0 with Spring , which had the job implementations as inner classes. The same can be accomplished with jobs defined as outer classes. The following method schedules the job.

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

private void sheduleMyJob() throws SchedulerException, ParseException {

        JobDetail job = newJob(com.shyarmal.quartz.daemon.jobs.MyJob.class)
                .withIdentity("my-job").build();
          
        Map dataMap = job.getJobDataMap();
        dataMap.put("quantity", quantity);
        dataMap.put("myService", myService);
        dataMap.put("unitPrice", unitPrice);

        CronTrigger trigger = newTrigger()
                .withIdentity("my-flag", "priority")
                .withSchedule(cronSchedule(chargeCronExpression)).forJob(job)
                .build();

        scheduler.scheduleJob(job, trigger);

        LOGGER.info("initialized scheduler with expression [{}] \n expression summary([{}]) ",
                trigger.getCronExpression(), trigger.getExpressionSummary());

}

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

JobDetail and CronTrigger initializations are the same as that in the previous example. Here the parameters to be passed are put to a job data map, which is obtained from JobDetails.
      "  Map dataMap = job.getJobDataMap();
        dataMap.put("quantity", quantity);
        dataMap.put("myService", myService);
        dataMap.put("unitPrice", unitPrice); "
 The scheduler is initialized in the same way as the previous example.

The job class may be of the following form.
=======================================================

package com.shyarmal.quartz.daemon.jobs;

import com.shyarmal.quartz.common.charging.service.IMyService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;


public class MyJob implements Job {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyJob.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        Map dataMap = context.getJobDetail().getJobDataMap();
        int quantity = (Integer) dataMap.get("quantity");
        IMyService myService = (IMyService) dataMap.get("myService");
        double unitPrice = (Double) dataMap.get("unitPrice");
        try {
            // implementation code of your task.
        } catch (Exception e) {
            LOGGER.error("Error occurred while doing job.", e);
        } finally {
            // implementation
        }
    }
}

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

JobDetails will be available through the JobExecutionContext passed in to the execute method of the job, from which the job data map can be retrieved. 
       " Map dataMap = context.getJobDetail().getJobDataMap();
        int quantity = (Integer) dataMap.get("quantity");
        IMyService myService = (IMyService) dataMap.get("myService");
        double unitPrice = (Double) dataMap.get("unitPrice"); "



thanks,
Shyarmal.

Web application context (spring load)

Following is an example of how spring beans can be loaded from a servlet. 

The web.xml configuration required is as follows. The spring bean definition xml file path should be given as a context parameter. Spring's ContextLoaderListener has to be defined as a listener in the web.xml. The sub-element 'load-on-startup' should be present in the servlet definition for the servlet to load at the web application is deploy time (If not the servlet will be initialized upon the first request to it).

 ==================================================================
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-beans.xml</param-value>
    </context-param>
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/log4j.xml</param-value>
        <description>location of log4j configuration file, used by log4jconfiglistener</description>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>com.shyarmal.servlet.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/init</url-pattern>
    </servlet-mapping>

</web-app>
 ==================================================================

The servlet code is below. The method, init(ServletConfig) [or init()] is overridden to load the web application context with, "WebApplicationContextUtils .getWebApplicationContext(config.getServletContext());". Servlet's init is called when the same is initialized.

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

package com.shyarmal.servlet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;



public class InitServlet extends HttpServlet {

    private static final Logger LOGGER = LoggerFactory.getLogger(InitServlet.class);

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            LOGGER.debug("initializing email service.");
            ApplicationContext ac = WebApplicationContextUtils              .getWebApplicationContext(config.getServletContext());
            LOGGER.info("Started email service.");
        } catch (Exception e) {
            LOGGER.error("Failed to load application context.", e);
        }
        super.init(config);
    }
}

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


thanks,
Shyarmal.


Wednesday, December 28, 2011

Open Session In View Filter Usage

Open Session In View Filter of Spring framework takes care of hibernate session management of a web application.  The integration of it is done at the web.xml.

Firstly, the spring beans ought to be loaded to the application context. This is done with a 'context-param' element. Secondly, define a filter with a 'filter' element (here my filter class is com.shyarmal.filter.MyOpenSessionInViewFilter which extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter).  Thirdly, define a filter mapping to the filter appropriately using 'filter-mapping' element. Notice the init parameter (sessionFactoryBeanName) passed to the filter. It is the id of the session factory defined in spring beans xml configurations.

web.xml elements of interest are as follows.
===================================================================
<context-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>/WEB-INF/springmvc-servlet.xml</param-value>
</context-param>

<filter>
   <filter-name>openSessionInViewFilter</filter-name>
   <filter-class>com.shyarmal.filter.MyOpenSessionInViewFilter</filter-class>
   <init-param>
        <param-name>sessionFactoryBeanName</param-name>
        <param-value>sessionFactory</param-value>
   </init-param>
</filter>

<filter-mapping>
        <filter-name>openSessionInViewFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
===================================================================

Following are the spring bean definitions related to session factory used for the integration of open session in view filter.
===================================================================

<bean id="hibernateConfigProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
   <property name="location">
       <value>classpath:hibernate.properties</value>
   </property>
</bean>

<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
   <property name="driverClassName" value="${jdbc.driver.class.name}"/>
   <property name="url" value="${jdbc.url}"/>
   <property name="username" value="${jdbc.username}"/>
   <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
        <list>
            <value>Accounts.hbm.xml</value>
             .....
            .....
            .....
        </list>
    </property>
    <property name="hibernateProperties" ref="hibernateConfigProperties"/>
</bean>

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

thanks,
Shyarmal.

Sunday, December 11, 2011

Read and display image - Java Swing


package com.shyarmal.image.display;

import java.awt.Color;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import javax.swing.ImageIcon;
import javax.swing.border.LineBorder;

/**
 *
 * @author  shyarmal
 * An external image file is read, re-sized and rendered in a
 * JLabel.
 */
public class ImageForm extends extends javax.swing.JFrame {

    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;


/**
This is the default constructor of the JFrame. This can not be used to render an image. Basically the initialization of components are done here. 
*/
    public ImageForm() {
        initComponents();
        this.setLocation(100, 150);
        jLabel1.setBorder(new LineBorder(Color.DARK_GRAY, 5));
        this.setResizable(false);
    }


/**
This is the constructor to be used to set an image. Path of the image file is passed as an argument, which is used to get an image icon from the method, createImageIcon(path) below. The image icon is set to the JLabel. Further the tile of the JFrame is set here. The default constructor is called first to initialize the components of the JFrame.
*/
    public ImageForm(String path) {
        this();
        this.setTitle("Image: " + path.substring(
                           path.lastIndexOf("\\") + 1));
        jLabel1.setIcon(createImageIcon(path));
//        jLabel1.setIcon(new ImageIcon(readFile(path)));
        getContentPane().add(jLabel1);
    }
/**
CREATING AND RESCALING OF AN IMAGE
An image is created from the byte data obtained by reading the image file (refer to the method, readImageFile(String path)). The image created is rescaled to the dimensions of the label in which it is to be rendered. An image icon is created from the rescaled image and returned.
*/
    private ImageIcon createImageIcon(String path) {
        Image image = new ImageIcon(
                readImageFile(path)).getImage();
        Image rescaledImage = image.getScaledInstance(
               jLabel1.getWidth(), jLabel1.getHeight(),
                      Image.SCALE_DEFAULT);
        return new ImageIcon(rescaledImage);
    }


/**
READING IMAGE DATA FROM (EXTERNAL) FILE
File path is passed into this method and a file input stream is created using the same. Length of byte data available in the input stream is obtained [fis.available()]. A byte array of the length, determined by this means is subsequently created. All the data is read into the byte array from the input stream [while ((i = fis.read(data)) != -1);] and returned.
*/
    private byte[] readImageFile(String path) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path);
            int length = fis.available();
            byte[] data = new byte[length];
            int i = 0;
            while ((i = fis.read(data)) != -1);
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }               
   
    //  auto generated codes for the JFrame are not shown.              
}




thanks,
Shyarmal.

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