Friday, February 14, 2014

Accessing Persistent Objects

In the previous article, I have discussed how to create session instance. This article demonstrates how session object can be used to access persistence objects, insert, update or remove objects.
[Assumption: we have session object, and we have to close transaction and session after we complete operation]

1) Insert, Update or Delete persistence object


2) Retrieve a collection of data
   i) If you want all persistent objects
       //using hibernate query
       List list=session.createQuery(HQL).list();
       //using sql 
       List list=session.createSQLquery(SQL).list();//gets raw
       List list=session.createSQLquery(SQL).addEntity(className).list();//entity objects

   ii) If you want selected object only (similar to WHERE clause in SQL)
     String HQL="SELECT * FROM ENTITY entity WHERE entity.fieldName=:fieldname";
     session.createQuery(HQL).setString(fieldname, value).list();
     For SQL, we create the sql query to get the list.      

    Criteria is more elegant for selection.
      Criteria criteria = session.createCriteria(className);
       criteria.add(, value));
       criteria.add(Restrictions.le(fieldName, value));
      // Also define union and intersection
       Disjunction disjunction = Restrictions.disjunction();
       disjunction.add(Restrictions.eq(fieldName, "#BLABLA#"));
       Conjunction conjunction=Restrictions.conjunciton();
       conjunction.add(Restrictions.eq(fieldName, "#BLABLA#"));

        criteria.setFetchMode("whatever", FetchMode.SELECT);

     List objects= criteria.list(); 

3) Retrieve specific object

We have to note here that all persistence objects have their own id. So,  with the id, we can get object

 Object object=session.get(className, id);

No comments:

Post a Comment