Knowledge Walls
J2EE Technologies Tutorial
Hyderabad, Andhra Pradesh, India
How to use CriteriaQuery and CriteriaBuilder of EntityManager in JPA Spring Hibernate Framework
1654 Views
Hints 
CriteriaQuery and CriteriaBuilder of EntityManager using with JPA.
Output: Browser 
Tomcat Console Log 
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: insert into STUDENT_INFO (STUDENT_NAME) values (?)
Hibernate: select studentinf0_.STUDENT_ID as STUDENT1_0_, studentinf0_.STUDENT_NAME as STUDENT2_0_ from STUDENT_INFO studentinf0_ where studentinf0_.STUDENT_NAME=? limit ?
{"studentId":7,"StudentName":"Student 7"}
Project Explorer Peview 
StudentInfo.java
package com.knowledgewalls.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity(name="STUDENT_INFO")
public class StudentInfo {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="STUDENT_ID")
    private int studentId;
    
    @Column(name="STUDENT_NAME")
    private String StudentName;
    
    public StudentInfo(){}
    
    public StudentInfo(int studentId,String StudentName){
        this.studentId = studentId;
        this.StudentName = StudentName;
    }
    
    public int getStudentId() {
        return studentId;
    }
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return StudentName;
    }
    public void setStudentName(String studentName) {
        StudentName = studentName;
    }
}
StudentInfoDAO.java
package com.knowledgewalls.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.knowledgewalls.entity.StudentInfo;

@Repository
@Transactional
public class StudentInfoDAO {
    
    @PersistenceContext
    EntityManager em;
    
    public void save10Students(){
        try {
            for (int i=1;i<=10;i++){
                StudentInfo studentInfo = new StudentInfo();
                    studentInfo.setStudentName("Student "+i);
                        
                em.persist(studentInfo);
            }
        }
        catch(Exception e){
            System.out.println("Insertion Failure.");
            e.printStackTrace();
        }
    }
    
    public StudentInfo getStudentByName(String studentName){
        try {
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<StudentInfo> criteria = builder.createQuery(StudentInfo.class);
            Root<StudentInfo> studentInfo = criteria.from(StudentInfo.class);
                criteria.where(builder.equal(studentInfo.get("StudentName"), studentName));
            
            return (StudentInfo) em.createQuery(criteria.select(studentInfo)).getSingleResult();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

package com.knowledgewalls.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.knowledgewalls.entity.StudentInfo;

@Repository
@Transactional
public class StudentInfoDAO {
    
    @PersistenceContext
    EntityManager em;
    
    public void save10Students(){
        try {
            for (int i=1;i<=10;i++){
                StudentInfo studentInfo = new StudentInfo();
                    studentInfo.setStudentName("Student "+i);
                        
                em.persist(studentInfo);
            }
        }
        catch(Exception e){
            System.out.println("Insertion Failure.");
            e.printStackTrace();
        }
    }
    
    public StudentInfo getStudentByName(String studentName){
        try {
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<StudentInfo> criteria = builder.createQuery(StudentInfo.class);
            Root<StudentInfo> studentInfo = criteria.from(StudentInfo.class);
                criteria.where(builder.equal(studentInfo.get("StudentName"), studentName));
            
            return (StudentInfo) em.createQuery(criteria.select(studentInfo)).getSingleResult();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
package com.knowledgewalls.dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.knowledgewalls.entity.StudentInfo;

@Repository
@Transactional
public class StudentInfoDAO {
   
    @PersistenceContext
    EntityManager em;
   
    public void save10Students(){
        try {
            for (int i=1;i<=10;i++){
                StudentInfo studentInfo = new StudentInfo();
                    studentInfo.setStudentName("Student "+i);
                       
                em.persist(studentInfo);
            }
        }
        catch(Exception e){
            System.out.println("Insertion Failure.");
            e.printStackTrace();
        }
    }
   
    public StudentInfo getStudentByName(String studentName){
        try {
            CriteriaBuilder builder = em.getCriteriaBuilder();
            CriteriaQuery<StudentInfo> criteria = builder.createQuery(StudentInfo.class);
            Root<StudentInfo> studentInfo = criteria.from(StudentInfo.class);
                criteria.where(builder.equal(studentInfo.get("StudentName"), studentName));
           
            return (StudentInfo) em.createQuery(criteria.select(studentInfo)).getSingleResult();
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
StudentInfoController.java
package com.knowledgewalls.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.knowledgewalls.dao.StudentInfoDAO;

@Controller
public class StudentInfoController {
    
    @Autowired
    StudentInfoDAO studentInfoDAO;
    
    private void displayObject(Object object) {
        if (object == null)
            System.out.println("Null");
        else
            System.out.println(new Gson().toJson(object));
    }
    
    @RequestMapping(value="/doRun",method=RequestMethod.GET)
    public @ResponseBody String addUsers(){
        {
            studentInfoDAO.save10Students();
            displayObject(studentInfoDAO.getStudentByName("Student 7"));
        }
        
        return "Saved and Retrieved by HQL";
        
    }
}
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" >

  <persistence-unit name="hibernatePersistenceUnit">
          <properties>
            <property name="hibernate.hbm2ddl.auto" value="create" />
        </properties>
  </persistence-unit>

</persistence>
Beans-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <context:component-scan base-package="com.knowledgewalls" />
    <mvc:annotation-driven />
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    <bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath*:persistence.xml" />
        <property name="persistenceUnitName" value="hibernatePersistenceUnit" />
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
    </bean>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="mysql" />
        <property name="initialSize" value="5" />
        <property name="maxActive" value="10" />
    </bean>
    
    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
        <property name="database" value="MYSQL"></property>
        <property name="showSql" value="true"></property>
        <property name="generateDdl" value="false"></property>
        <property name="databasePlatform" value="org.hibernate.dialect.MySQL5InnoDBDialect"></property>
    </bean>
    
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
         <property name="entityManagerFactory" ref="emf" />
    </bean>
    
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

</beans>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Hibernate024_CriteriaQueries</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <servlet>
    <servlet-name>beans</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>beans</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>
Output: SQL
drop table if exists STUDENT_INFO;
create table STUDENT_INFO (STUDENT_ID integer not null auto_increment, STUDENT_NAME varchar(255), primary key (STUDENT_ID)) ENGINE=InnoDB;
Best Lessons of "Hibernate 3.0 Examples"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details