Sunday, June 16, 2013

31 - Projections-and-Query-By-Example

Criteria criteria = session.createCriteria(UserDetails.class).setProjection(Projections.property("userId"));
It pull up only one record

Criteria criteria = session.createCriteria(UserDetails.class).setProjection(Projections.max("userId"));
It returns max userid

Criteria criteria = session.createCriteria(UserDetails.class).setProjection(Projections.count("userId"));
It returns count of userIds

Criteria criteria = session.createCriteria(UserDetails.class).addOrder(Order.desc("userId"));
It returns the records in descending order

Suppose I want to pull the recrods with different conditions or too many properties or criterias like userid, name, pincode etc. Creating a criteria object with all the objects is painful job. Handy way to do this by using "Example" criteria
eg.
                UserDetails exammpleUser = new UserDetails();
                exampleUser.setUserId(5);
                exampleUser.seUsername("User 5");
                Example example = Example.create(exampleUser);
                Criteria criteria = session.createCriteria(UserDetails.class).add(example);

Hibernate ignore two things when it come to Example
1. It ignores if any of the properties has NULL value
2. It ignores Primary key of the table      
While pulling the data hibernate ignore above properties

Suppose you want to ignore some property you can do using below
Example example = Example.create(exampleUser).excludeProperty("userName");

exampleUser.seUsername("User 5%");
Example example = Example.create(exampleUser).enableLike();

HibernateTest.java
package org.yash.hibernate;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.yash.dto.UserDetails;

public class HibernateTest {

      public static void main(String args[]) {
           
            SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
            Session session = sessionFactory.openSession();
            session.beginTransaction();

            UserDetails exampleUser = new UserDetails();
            //exampleUser.setUserId(16);
            //exampleUser.setUserName("User 1");
            exampleUser.setUserName("%User 1%");
           
            //Example example = Example.create(exampleUser);
            Example example = Example.create(exampleUser).enableLike();
            //Example example = Example.create(exampleUser).excludeProperty("userName");
            Criteria criteria = session.createCriteria(UserDetails.class)
                                          .add(example);
           
            //Criteria criteria = session.createCriteria(UserDetails.class)
                                          //.setProjection(Projections.max("userId"));
                                          //.addOrder(Order.desc("userId"));
            criteria.add(Restrictions.or(Restrictions.between("userId",10,13), Restrictions.between("userId", 17, 20)));
           
            List<UserDetails> users = (List<UserDetails>)criteria.list();          
            session.getTransaction().commit();
            session.close();
           
            for(UserDetails u:users){
                  System.out.println(u.getUserName());
            }
           

      }
}

UserDetails.java
package org.yash.dto;

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

@Entity
@NamedQuery(name="UserDetails.byId", query="from UserDetails where userId = ?") //HQL query - based on class name
@org.hibernate.annotations.Entity(selectBeforeUpdate=true)
public class UserDetails {
      /* @Id says "userId" is primary key */
      @Id @GeneratedValue (strategy=GenerationType.AUTO)
      private int userId;    
      private String userName;
      @OneToMany(cascade=CascadeType.PERSIST)
      private Collection<Vehicle> vehicle = new ArrayList<Vehicle>();
           
      public int getUserId() {
            return userId;
      }
      public void setUserId(int userId) {
            this.userId = userId;
      }
      public String getUserName() {
            return userName;
      }
      public void setUserName(String userName) {
            this.userName = userName;
      }
      public void setVehicle(Collection<Vehicle> vehicle) {
            this.vehicle = vehicle;
      }
      public Collection<Vehicle> getVehicle() {
            return vehicle;
      }
}

hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <property name="connection.driver_class">
            org.postgresql.Driver
        </property>
        <property name="connection.url">
            jdbc:postgresql://localhost:5433/hibernatedb
        </property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">admin</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">
            org.hibernate.dialect.PostgreSQLDialect
        </property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
       
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
       
        <!-- Drop and re-create the database schema on startup -->
            <property name="hbm2ddl.auto">update</property> 
<!-- create / update -->
   
          <!-- Names the annotated entity class -->
            <mapping class="org.yash.dto.UserDetails"/>    
           
    </session-factory>

</hibernate-configuration>

No comments:

Post a Comment