Requirement Constraints

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Thursday, 24 May 2012

Hibernate Criteria Queries

Posted on 13:57 by Unknown
The Hibernate Session interface provides createCriteria() method which can be used to create a Criteria object that returns instances of the persistence object's class when your application executes a criteria query

Environment

  1. Eclipse 3.7 Indigo IDE
  2. Hibernate 4.1.1
  3. JavaSE 1.6
  4. MySQL 5.1

Step 1:

Create the following table in mysql
image
Insert the records as follows
image

Step 3:

In the Eclipse, Select File –> New –> Java Project and give Project Name as HibernateCriteria
Click Next –> Go to Libraries Tab-> Click External Jar Files and include the following jar files
  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

Step 4:

Create the Employee POJO Class as follows
image
  1:  package mypack;
 
   3:  import javax.persistence.Entity;
   4:  import javax.persistence.GeneratedValue;
   5:  import javax.persistence.Id;
   6:  import javax.persistence.Table;
   7:  import javax.persistence.Column;
   8:   
   9:   
  10:  @Entity
  11:  @Table(name="employee")
  12:  public class Employee {
  13:      private int id;
  14:      private String firstName;
  15:      private String lastName;
  16:      private int salary;
  17:      private int IsActive;
  18:   
  19:      public Employee() {
  20:      }
  21:   
  22:      public Employee(String fname, String lname, int salary) {
  23:          this.firstName = fname;
  24:          this.lastName = lname;
  25:          this.salary = salary;
  26:      }
  27:   
  28:      @Id
  29:      @GeneratedValue
  30:      @Column(name="ID")
  31:      public int getId() {
  32:          return id;
  33:      }
  34:   
  35:      public void setId(int id) {
  36:          this.id = id;
  37:      }
  38:   
  39:      @Column(name="firstName")
  40:      public String getFirstName() {
  41:          return firstName;
  42:      }
  43:   
  44:      public void setFirstName(String first_name) {
  45:          this.firstName = first_name;
  46:      }
  47:   
  48:      @Column(name="lastName")
  49:      public String getLastName() {
  50:          return lastName;
  51:      }
  52:   
  53:      public void setLastName(String last_name) {
  54:          this.lastName = last_name;
  55:      }
  56:   
  57:      @Column(name="salary")
  58:      public int getSalary() {
  59:          return salary;
  60:      }
  61:   
  62:      public void setSalary(int salary) {
  63:          this.salary = salary;
  64:      }
  65:      
  66:      @Column(name="IsActive")
  67:      public int getIsActive() {
  68:          return IsActive;
  69:      }
  70:   
  71:      public void setIsActive(int IsActive) {
  72:          this.IsActive = IsActive;
  73:      }
  74:   
  75:  }
 

Step 5:


Let us create Hibernate Configuration file hibernate.cfg.xml




   1: <?xml version="1.0" encoding="utf-8"?>
   2: <!DOCTYPE hibernate-configuration PUBLIC
   3:  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
   4:  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
   5: <hibernate-configuration>
   6:     <session-factory>
   7:         <!-- Database connection settings -->
   8:         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
   9:         <property name="connection.url">jdbc:mysql://localhost/sampledb</property>
  10:         <property name="connection.username">root</property>
  11:         <property name="connection.password">123</property>
  12:  
  13:         <!-- JDBC connection pool (use the built-in) -->
  14:         <property name="connection.pool_size">1</property>
  15:  
  16:         <!-- SQL dialect -->
  17:         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  18:  
  19:         <!-- Enable Hibernate's automatic session context management -->
  20:         <property name="current_session_context_class">thread</property>
  21:  
  22:         <!-- Disable the second-level cache -->
  23:         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
  24:  
  25:         <!-- Echo all executed SQL to stdout -->
  26:         <property name="show_sql">true</property>
  27:  
  28:         <!-- Drop and re-create the database schema on startup -->
  29:         <property name="hbm2ddl.auto">update</property>
  30:  
  31:         <!-- Mapping Classes -->
  32:         <mapping class="mypack.Employee" />
  33:  
  34:     </session-factory>
  35: </hibernate-configuration>

Take care to change the DB Name, User name and Password according to your setup


Step 6:




Next we will create our Test.java in which we are going to test different Hibernate Criteria Queries

image

Here is the Code





   1: package mypack;
   2:  
   3: import java.util.List;
   4: import org.hibernate.Criteria;
   5: import org.hibernate.Query;
   6: import org.hibernate.Session;
   7: import org.hibernate.SessionFactory;
   8: import org.hibernate.Transaction;
   9: import org.hibernate.cfg.Configuration;
  10: import org.hibernate.service.ServiceRegistry;
  11: import org.hibernate.service.ServiceRegistryBuilder;
  12: import org.hibernate.HibernateException;
  13:  
  14: public class Test {
  15:  
  16:     private static SessionFactory factory;
  17:     private static ServiceRegistry serviceRegistry;
  18:  
  19:     public static void main(String[] args) {
  20:         getAllRecords();
  21:     }
  22:  
  23:     public static void getAllRecords() {
  24:         try {
  25:             Configuration configuration = new Configuration();
  26:             configuration.configure();
  27:             serviceRegistry = new ServiceRegistryBuilder().applySettings(
  28:                     configuration.getProperties()).buildServiceRegistry();
  29:             factory = configuration.buildSessionFactory(serviceRegistry);
  30:         } catch (Throwable ex) {
  31:             System.err.println("Failed to create sessionFactory object." + ex);
  32:             throw new ExceptionInInitializerError(ex);
  33:         }
  34:         System.out.println("**Example : Hibernate  SessionFactory**");
  35:         System.out.println("----------------------------------------");
  36:         Session session = factory.openSession();
  37:         Transaction tx = null;
  38:         try {
  39:             tx = session.beginTransaction();
  40:             Criteria cr = session.createCriteria(Employee.class);
  41:             List results = cr.list();
  42:             for (int i = 0; i < results.size(); i++) {
  43:                 Employee emp = (Employee) results.get(i);
  44:                 System.out.println(emp.getFirstName());
  45:             }
  46:             tx.commit();
  47:         } catch (HibernateException e) {
  48:             if (tx != null)
  49:                 tx.rollback();
  50:             e.printStackTrace();
  51:         } finally {
  52:             session.close();
  53:         }
  54:     }
  55: }


Step 7:




Now let us run the Test.Java as Java Application

In the console,  did you see the following errorSad smile 

----------------------------------------
Hibernate: select this_.ID as ID0_0_, this_.firstName as firstName0_0_, this_.IsActive as IsActive0_0_, this_.lastName as lastName0_0_, this_.salary as salary0_0_ from employee this_
org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type setter of mypack.Employee.isActive





If one declares these int,bit,char as Primitive data types in POJO classes.. then we cannot do getter/setter NULL value into this attributes.. but on you these values will allow NULL to store.. so to avoid this conflicts its always suggestible to use WRAPPER classes itself not Primitive types.
So, We would need to initialize these variable with WRAPPER classes only
like int - "Integer"
bit - "Boolean"
char - "Character"




So we will change our POJO Class, because we have two columns where null value are stored and that has been declared as int. So let us change to integer.

Here is the code





   1: package mypack;
   2: import javax.persistence.Entity;
   3: import javax.persistence.GeneratedValue;
   4: import javax.persistence.Id;
   5: import javax.persistence.Table;
   6: import javax.persistence.Column;
   7:  
   8: @Entity
   9: @Table(name="employee")
  10: public class Employee {
  11:     private int id;
  12:     private String firstName;
  13:     private String lastName;
  14:     private Integer salary;
  15:     private Integer IsActive;
  16:  
  17:     public Employee() {
  18:     }
  19:  
  20:     public Employee(String fname, String lname, int salary) {
  21:         this.firstName = fname;
  22:         this.lastName = lname;
  23:         this.salary = salary;
  24:     }
  25:     @Id
  26:     @GeneratedValue
  27:     @Column(name="ID")
  28:     public int getId() {
  29:         return id;
  30:     }
  31:  
  32:     public void setId(int id) {
  33:         this.id = id;
  34:     }
  35:  
  36:     @Column(name="firstName")
  37:     public String getFirstName() {
  38:         return firstName;
  39:     }
  40:  
  41:     public void setFirstName(String first_name) {
  42:         this.firstName = first_name;
  43:     }
  44:  
  45:     @Column(name="lastName")
  46:     public String getLastName() {
  47:         return lastName;
  48:     }
  49:  
  50:     public void setLastName(String last_name) {
  51:         this.lastName = last_name;
  52:     }
  53:  
  54:     @Column(name="salary")
  55:     public Integer getSalary() {
  56:         return salary;
  57:     }
  58:  
  59:     public void setSalary(Integer salary) {
  60:         this.salary = salary;
  61:     }
  62:     
  63:     @Column(name="IsActive")
  64:     public Integer getIsActive() {
  65:         return IsActive;
  66:     }
  67:  
  68:     public void setIsActive(Integer IsActive) {
  69:         this.IsActive = IsActive;
  70:     }
  71: }

Now let us again run the Test.Java as Java Application

Wow!!!! Smile, Output as follows
**Example : Hibernate  SessionFactory**
----------------------------------------
Hibernate: select this_.ID as ID0_0_, this_.firstName as firstName0_0_, this_.IsActive as IsActive0_0_, this_.lastName as lastName0_0_, this_.salary as salary0_0_ from employee this_
John
Robert
Richard
Anderson
Lee
Nelson




Step 8:




Now let us see how we can retrieve all the Active Employee.

image


Here Anderson is active. And also let us consider if that column contains null value, then we will treat that also Active Employees.Here is the Criteria





   1: Criteria cr = session.createCriteria(Employee.class);
   2:             Criterion cr1 = Restrictions.eq("isActive", 1);
   3:             Criterion cr2 = Restrictions.isNull("isActive");
   4:             // To get records matching with OR condistions
   5:             LogicalExpression orExp = Restrictions.or(cr1, cr2);
   6:             cr.add( orExp );
   7:             List results = cr.list();
Assume that we need only Inactive Employee. So as per the records, there are two employee (b’0’)

Criteria cr = session.createCriteria(Employee.class);
        cr.add(Restrictions.eq("isActive", 0));
        List results = cr.list();
Email ThisBlogThis!Share to XShare to Facebook
Posted in Hibernate Criteria Queries | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • ZK Example for inline Editing with Add New and Delete
    I am quite impressed on this demo from ZK . But adding new record and delete existing record is missing as part of typical CRUD. So i thoug...
  • EDI 5010 Documentation 837 Professional - Loop 2010BB Payer Name
    2010BB Payer Name          In this loop, all the information will be taken from Insurance master screen. Take a look of our sample screen...
  • EDI 5010 Documentation–837 - BHT - Beginning of Hierarchical Transaction
    BHT – Beginning of Hierarchical Transaction Loop Seg ID Segment Name Format Length Ref# Req Value   BHT Beginning of Hier...
  • Hibernate Validator Example 2
    In this example, we will see some more validation constraints such as @email, @past, @length, etc. And also we will also define custom error...
  • ZK Passing Parameter between two files using MVVM–Part 1
    Overview This is the first series of articles about Passing parameter between two zul files using MVVM Design pattern .This article will fo...
  • MVVM Command annotation and Notify change example
    Here is an example, how to pass parameter on a zul through MVVM Command binding annotation. ZK URL http://books.zkoss.org/wiki/ZK%20Develo...
  • History of Present Illness
    HPI - One of the main component of Clinical History. What is an HPI ? The history of present illness (HPI) is a chronological description...
  • Patient Demographics
    Patient browse (search) is the key element for any EMR / PMS Software. In my past 15 years experience, i involved more than 5 times in desig...
  • ViewModel Class Java Annotation @Init, @NotifyChange, @Command
    In following sections we'll list all syntaxes that can be used in implementing a ViewModel and applying ZK bind annotation. The ZK binde...
  • Good Website Design Links
    Form Design Label Placement in Forms International Address Fields in Web Forms 40 Eye-Catching Registration Pages blog-comment-form-...

Categories

  • Billing Process
  • C Workbook
  • C++ Workbook
  • Eclipse Tips
  • EDI 5010
  • EMR Appointment Features
  • EMR Labs Stuff
  • EMR PMS Links
  • EMR Use cases
  • EMR Vital Sign
  • Good Website Design
  • Hibernate Criteria Queries
  • Hibernate Introduction
  • Hibernate Introduction Setup
  • Hibernate Mapping
  • Hibernate POC
  • Hibernate Validator
  • Hibernate–Java Environment setup
  • HPI
  • Java
  • Maven
  • MU Certification
  • NPI
  • PQRS
  • Practice Management System
  • Spring Security
  • Tech Links
  • Today Tech Stuff
  • zk
  • ZK Hibernate
  • ZK 5 Databinding
  • ZK Application
  • ZK Calling Another ZUL
  • ZK CheckBox
  • ZK CreateComponents
  • ZK CSS
  • ZK extended Components
  • ZK Foreach
  • ZK Forum Posts
  • ZK Framework
  • ZK Hibernate Setup
  • ZK ID Space
  • ZK Include
  • ZK Installation
  • ZK iReport
  • ZK Layout
  • ZK Listitem Pagination
  • ZK Message Box
  • ZK MVC
  • ZK MVC Combox Box
  • ZK MVC CRUD Examples
  • ZK MVC Listbox
  • ZK MVVM
  • ZK MVVM Combo
  • ZK MVVM CRUD
  • ZK MVVM ListBox
  • ZK Spring
  • ZK TextBox

Blog Archive

  • ►  2013 (105)
    • ►  December (3)
    • ►  September (7)
    • ►  August (13)
    • ►  July (1)
    • ►  June (11)
    • ►  May (3)
    • ►  April (14)
    • ►  March (19)
    • ►  February (21)
    • ►  January (13)
  • ▼  2012 (177)
    • ►  December (1)
    • ►  November (13)
    • ►  October (19)
    • ►  September (24)
    • ►  August (26)
    • ►  July (6)
    • ►  June (37)
    • ▼  May (30)
      • Input Form Validation window
      • ZK Executions.createComponents
      • List Item Connected with Hibernate and Search Para...
      • ZK Hibernate Setup
      • Window Title Change Color
      • List item Data Binding
      • ZK Data Binding
      • Message Box Customization
      • MVC CRUD Application–Filter records in the list ba...
      • ZK Check Event Handling Using MVC
      • MVC CRUD Application with Auto filter for List item
      • Text Box on change and on Changing Event
      • Hibernate Criteria Queries
      • MVC CRUD Application
      • Hibernate Query uniqueResult Method
      • Hibernate retrieve the first record always when we...
      • Hibernate Introduction Part 4
      • ZK Data Binding Part 1
      • Simple Sightseeing Application Part 2
      • Window CSS
      • ZK Simple Sightseeing Application Part 1
      • Button CSS
      • Group Box with Collapse and Expand Button in the R...
      • Tuning Eclipse Performance and Avoiding OutOfMemor...
      • Listitem Mold Paging - Add components in the pagin...
      • ZK Calling Another ZUL File
      • ZK Installation Guide
      • List Box CSS
      • Eclipse Tips and Tricks
      • Hibernate Introduction Part 3
    • ►  April (16)
    • ►  March (1)
    • ►  January (4)
  • ►  2011 (5)
    • ►  December (1)
    • ►  November (1)
    • ►  July (1)
    • ►  June (1)
    • ►  April (1)
  • ►  2010 (1)
    • ►  September (1)
Powered by Blogger.

About Me

Unknown
View my complete profile