☰ See All Chapters |
JPA Criteria API
Criteria API was introduced in JPA 2.0. Using this API we can define queries dynamically via construction of an object-based javax.persistence.CriteriaQuery instance rather than string-based approach used in JPQL (Java Persistence Query Language).
Constructing a CriteriaQuery
Step 1: Create CriteriaBuilder object by invoking getCriteriaBuilder() method of EntityManager.
CriteriaBuilder cb = em.getCriteriaBuilder();
Step 2: Create an instance of CriteriaQuery interface to create a query object.
CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
Step 3: Specify query roots by invoking from() method of CriteriaQuery. Query roots specify the domain objects on which the query is evaluated.
Root<Student> from = criteriaQuery.from(Student.class);
Step 4: Call the select method of CriteriaQuery Object to specify type of query result.
criteriaQuery.select(from);
Step 6: Create the Predicate by calling the restriction methods of CriteriaBuilder. Here we are putting a restriction to select sname which is equal to Manu Manjunatha.
Predicate predicate = cb.equal(from.get("sname"), "Manu Manjunatha");
Step 7: Apply the Predicate by invoking where method of CriteriaQuery.
criteriaQuery.where(predicate);
JPA Criteria Example
Database script (MySQL)
CREATE TABLE ADDRESS( AID INT(5) PRIMARY KEY AUTO_INCREMENT, CITY VARCHAR(30), ZIPCODE VARCHAR(30) );
CREATE TABLE STUDENT( SID INT(5) PRIMARY KEY AUTO_INCREMENT, SNAME VARCHAR(30), AID INT(5), CONSTRAINT FOREIGN KEY (AID) REFERENCES ADDRESS (AID) );
INSERT INTO ADDRESS(AID,CITY,ZIPCODE) VALUES (1,'Bangalore', '560010');
INSERT INTO STUDENT(SID,SNAME,AID) VALUES (1,'Manu Manjunatha', 1); INSERT INTO STUDENT(SID,SNAME,AID) VALUES (2,'Advith Tyagraj', 1); INSERT INTO STUDENT(SID,SNAME,AID) VALUES (3,'Likitha', 1); INSERT INTO STUDENT(SID,SNAME,AID) VALUES (4,'Tyagraj', 1); |
pom.xml
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.java4coding</groupId> <artifactId>JPA_Criteria</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>JPA_Criteria</name> <url>https://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>javax.persistence</artifactId> <version>2.0.0</version> </dependency>
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>4.2.8.Final</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.11</version> </dependency> </dependencies> </project> |
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="https://java.sun.com/xml/ns/persistence" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://java.sun.com/xml/ns/persistence https://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">
<persistence-unit name="StudentPU"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <properties> <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/study" /> <property name="hibernate.connection.driver_class" value="com.mysql.cj.jdbc.Driver" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.archive.autodetection" value="class" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence> |
Address.java
package com.java4coding;
import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table;
@Entity @Table(name = "ADDRESS") public class Address {
@Id private int aid;
private String city;
private String zipcode;
public int getAid() { return aid; } public void setAid(int aid) { this.aid = aid; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } } |
Student.java
package com.java4coding;
import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table;
@Entity @Table(name = "STUDENT") public class Student {
@Id @GeneratedValue(strategy = GenerationType.AUTO) private int sid;
private String sname;
@ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name= "AID") private Address address;
public int getSid() { return sid; } public void setSid(int sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } |
Test.java
package com.java4coding;
import java.util.List;
import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root;
public class Test { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("StudentPU"); EntityManager em = emf.createEntityManager(); em.getTransaction().begin();
//Create CriteriaBuilder object by invoking getCriteriaBuilder() method of EntityManager. CriteriaBuilder cb = em.getCriteriaBuilder();
//Create an instance of CriteriaQuery interface to create a query object. CriteriaQuery<Student> criteriaQuery = cb.createQuery(Student.class);
//Specify query roots by invoking from() method of CriteriaQuery //query roots specify the domain objects on which the query is evaluated. Root<Student> from = criteriaQuery.from(Student.class);
//Call the select method of CriteriaQuery Object to specify type of query result. criteriaQuery.select(from);
//Create the Predicate by calling the restriction methods of CriteriaBuilder. //Here we are putting a restriction to select sname which is equal to Manu Manjunatha Predicate predicate = cb.equal(from.get("sname"), "Manu Manjunatha");
//Apply the Predicate by invoking where method of CriteriaQuery criteriaQuery.where(predicate);
List<Student> results = em.createQuery(criteriaQuery).getResultList();
for(Student s: results) { System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); if (s.getSname() != null) { System.out.println("Student name: " + s.getSname()); } if (s.getSid() != 0) { System.out.println("Student ID: " + s.getSid()); } if (s.getAddress().getCity() != null) { System.out.println("Student City: " + s.getAddress().getCity()); } if (s.getAddress().getCity() != null) { System.out.println("Student City: " + s.getAddress().getCity()); } if (s.getAddress().getZipcode() != null) { System.out.println("Student Zipcode: " + s.getAddress().getZipcode()); } System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" ); }
em.getTransaction().commit(); } } |
Project directory structure
Output:
Hibernate: select student0_.sid as sid1_1_, student0_.AID as AID3_1_, student0_.sname as sname2_1_ from STUDENT student0_ where student0_.sname=? Hibernate: select address0_.aid as aid1_0_0_, address0_.city as city2_0_0_, address0_.zipcode as zipcode3_0_0_ from ADDRESS address0_ where address0_.aid=? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Student name: Manu Manjunatha Student ID: 1 Student City: Bangalore Student City: Bangalore Student Zipcode: 560010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
All Chapters