Sunday, 6 September 2020

How To Use Criteria in Hibernate 5

Hibernate Criteria Query API In Hibernate 5


Hibernate provide Criteria API to manipulating  the objects in type safe manner . Hibernate Criteria API introduce many changes how can you create criteria query .In Hibernate 5 To Create Criteria query you have write following code

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<MensWear> criteriaQuery = criteriaBuilder.createQuery(MensWear.class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);
criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("productId"), 1));
Query<MensWear> query = session.createQuery(criteriaQuery); 


Hibernate Criteria Query example to fetch data using criteria query .

MensWear.java

package in.jk.hibernate5.criteria.api.query;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "hibernate5_mens_wears")
public class MensWear {

@Id
@Column(name = "product_id")
private int productId;
@Column(name = "product_name")
private String productName;
@Column(name = "company")
private String company;
@Column(name = "product_type")
private String productType;
@Column(name = "price")
private String price;
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getProductType() {
return productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
@Override
public String toString() {
return "MensWear [productId=" + productId + ", productName=" + productName + ", company=" + company
+ ", productType=" + productType + ", price=" + price + "]";
}

}


HibernateUtils.java

package in.jk.hibernate5;

import java.util.HashMap;
import java.util.Map;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.BootstrapServiceRegistry;
import org.hibernate.boot.registry.BootstrapServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;

public class HibernateUtils {

private static StandardServiceRegistry standardServiceRegistry = null;
private static SessionFactory sessionFactory = null;
        
       public static SessionFactory getSessionFactory() {

return sessionFactory;

}

// SessionFactory using java config
public static SessionFactory buildSessionFactory() {
 
                StandardServiceRegistryBuilder serviceRegistryBuilder = null;

// Session Factory Service To Config and Integrate Hibernate Listener


serviceRegistryBuilder = new  StandardServiceRegistryBuilder();
Map<String, String> hibernateProperties = new HashMap<String, String>();

hibernateProperties.put(Environment.DRIVER, "org.postgresql.Driver");
hibernateProperties.put(Environment.URL, "jdbc:postgresql://localhost:5432/postgres");
hibernateProperties.put(Environment.USER, "postgres");
hibernateProperties.put(Environment.PASS, "jk123");
hibernateProperties.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
hibernateProperties.put(Environment.SHOW_SQL, "true");
hibernateProperties.put(Environment.HBM2DDL_AUTO, "update");

serviceRegistryBuilder.applySettings(hibernateProperties);
standardServiceRegistry = serviceRegistryBuilder.build();
MetadataSources metadataSources = new MetadataSources(standardServiceRegistry);

                // Criteria API Query
metadataSources.addAnnotatedClass(in.jk.hibernate5.criteria.api.query.MensWear.class);
                Metadata metadata = metadataSources.getMetadataBuilder().build();
                sessionFactory = metadata.getSessionFactoryBuilder().build();
                return sessionFactory;

}

}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Hibernate5withJava</groupId>
<artifactId>Hibernate5withJava</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/postgresql/postgresql -->
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.2.10.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.ehcache/ehcache -->
<dependency>
<groupId>org.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

CriteriaQueryAPIHibernate5Application .java

package in.jk.hibernate5.criteria.api.query;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Root;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import in.jk.hibernate5.HibernateUtils;

public class CriteriaQueryAPIHibernate5Application {

private static SessionFactory sessionFactory;

public static void main(String[] args) {

sessionFactory = HibernateUtils.buildSessionFactory();
CriteriaQueryAPIHibernate5Application.addProduct();
System.out.println("\n ---------Find Product By ProductId --------  \n");
CriteriaQueryAPIHibernate5Application.findProdcutById();
System.out.println("\n -------  Find Product Name ---------- \n");
CriteriaQueryAPIHibernate5Application.findProdcutName();
System.out.println("\n ---------Find Product By Name and Comapny ------------ \n");
CriteriaQueryAPIHibernate5Application.findProdcutNameAndCompany();
System.out.println("\n-----------Find Product Info   -------------------\n");
CriteriaQueryAPIHibernate5Application.findProdcutDataWithMultiSelect();
System.out.println("\n-----------Find All Product  -------------------- \n");
CriteriaQueryAPIHibernate5Application.findAllProdcut();

}

private static void addProduct() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

MensWear mensWear1 = new MensWear();
mensWear1.setProductId(1);
mensWear1.setProductName("Active Chill");
mensWear1.setCompany("Reebok");
mensWear1.setProductType("T-Shirts");
mensWear1.setPrice("2300");

MensWear mensWear2 = new MensWear();
mensWear2.setProductId(2);
mensWear2.setProductName("Sweet Animal");
mensWear2.setCompany("Reebok");
mensWear2.setProductType("T-Shirts");
mensWear2.setPrice("1799");

MensWear mensWear3 = new MensWear();
mensWear3.setProductId(3);
mensWear3.setProductName("Addidas ZNE");
mensWear3.setCompany("Addidas");
mensWear3.setProductType("Hoody");
mensWear3.setPrice("6999");

MensWear mensWear4 = new MensWear();
mensWear4.setProductId(4);
mensWear4.setProductName("Skull Cap");
mensWear4.setCompany("Reebok");
mensWear4.setProductType("Cap");
mensWear4.setPrice("1499");

session.persist(mensWear1);
session.persist(mensWear2);
session.persist(mensWear3);
session.persist(mensWear4);

transaction.commit();
session.close();

System.out.println("Mens Wear Prodcut add Succussfully ...");
}

private static void findProdcutById() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<MensWear> criteriaQuery = criteriaBuilder.createQuery(MensWear.class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);

criteriaQuery.select(root).where(criteriaBuilder.equal(root.get("productId"), 1));

Query<MensWear> query = session.createQuery(criteriaQuery);

MensWear mensWear = query.uniqueResult();
System.out.println("MensWear :: " + mensWear);

transaction.commit();
session.close();
}


private static void findProdcutName() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<String> criteriaQuery = criteriaBuilder.createQuery(String.class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);

criteriaQuery.select(root.get("productName"));

Query<String> query = session.createQuery(criteriaQuery);

System.out.println("MensWear Product Name :: ");

query.list().forEach(System.out::println);

transaction.commit();
session.close();
}
private static void findProdcutNameAndCompany() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);
Path<Object> prdouctName = root.get("productName");
Path<Object> company = root.get("company");

criteriaQuery.select(criteriaBuilder.array(prdouctName,company));

Query<Object[]> query = session.createQuery(criteriaQuery);

System.out.println("MensWear Product Name  :: ");

query.list().forEach(product->{
System.out.println("Name    ::  "+product[0]);
System.out.println("Comapny ::   "+product[1]);
});

System.out.println();
transaction.commit();
session.close();
}
private static void findProdcutDataWithMultiSelect() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<Object[]> criteriaQuery = criteriaBuilder.createQuery(Object[].class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);
Path<Object> prdouctName = root.get("productName");
Path<Object> company = root.get("company");
Path<Object> price = root.get("price");

criteriaQuery.multiselect(prdouctName,company,price);

Query<Object[]> query = session.createQuery(criteriaQuery);

System.out.println("MensWear Product Name  :: ");

query.list().forEach(product->{
System.out.println("Name    ::  "+product[0]);
System.out.println("Comapny ::   "+product[1]);
System.out.println("Price   ::   "+product[2]);
System.out.println();
});

System.out.println();
transaction.commit();
session.close();
}

private static void findAllProdcut() {

Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

CriteriaBuilder criteriaBuilder = session.getCriteriaBuilder();
CriteriaQuery<MensWear> criteriaQuery = criteriaBuilder.createQuery(MensWear.class);
Root<MensWear> root = criteriaQuery.from(MensWear.class);

criteriaQuery.select(root);

Query<MensWear> query = session.createQuery(criteriaQuery);

List<MensWear> mensWears = query.getResultList();
System.out.println("All MensWear Product :: ");
mensWears.forEach(System.out::println);

transaction.commit();
session.close();
}

}


---------------------------------------------------------
Output in console

Hibernate: create table hibernate5_mens_wears (product_id int4 not null, company varchar(255), price varchar(255), product_name varchar(255), product_type varchar(255), primary key (product_id))
Sep 05, 2020 2:00:15 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
Hibernate: insert into hibernate5_mens_wears (company, price, product_name, product_type, product_id) values (?, ?, ?, ?, ?)
Hibernate: insert into hibernate5_mens_wears (company, price, product_name, product_type, product_id) values (?, ?, ?, ?, ?)
Hibernate: insert into hibernate5_mens_wears (company, price, product_name, product_type, product_id) values (?, ?, ?, ?, ?)
Hibernate: insert into hibernate5_mens_wears (company, price, product_name, product_type, product_id) values (?, ?, ?, ?, ?)
Mens Wear Prodcut add Succussfully ...

 ---------Find Product By ProductId --------  

Hibernate: select menswear0_.product_id as product_1_22_, menswear0_.company as company2_22_, menswear0_.price as price3_22_, menswear0_.product_name as product_4_22_, menswear0_.product_type as product_5_22_ from hibernate5_mens_wears menswear0_ where menswear0_.product_id=1
MensWear :: MensWear [productId=1, productName=Active Chill, company=Reebok, productType=T-Shirts, price=2300]

 -------  Find Product Name ---------- 

MensWear Product Name :: 
Hibernate: select menswear0_.product_name as col_0_0_ from hibernate5_mens_wears menswear0_
Active Chill
Sweet Animal
Addidas ZNE
Skull Cap

 ---------Find Product By Name and Comapny ------------ 

MensWear Product Name  :: 
Hibernate: select menswear0_.product_name as col_0_0_, menswear0_.company as col_1_0_ from hibernate5_mens_wears menswear0_
Name    ::  Active Chill
Comapny ::   Reebok
Name    ::  Sweet Animal
Comapny ::   Reebok
Name    ::  Addidas ZNE
Comapny ::   Addidas
Name    ::  Skull Cap
Comapny ::   Reebok


-----------Find Product Info   -------------------

MensWear Product Name  :: 
Hibernate: select menswear0_.product_name as col_0_0_, menswear0_.company as col_1_0_, menswear0_.price as col_2_0_ from hibernate5_mens_wears menswear0_
Name    ::  Active Chill
Comapny ::   Reebok
Price   ::   2300

Name    ::  Sweet Animal
Comapny ::   Reebok
Price   ::   1799

Name    ::  Addidas ZNE
Comapny ::   Addidas
Price   ::   6999

Name    ::  Skull Cap
Comapny ::   Reebok
Price   ::   1499



-----------Find All Product  -------------------- 

Hibernate: select menswear0_.product_id as product_1_22_, menswear0_.company as company2_22_, menswear0_.price as price3_22_, menswear0_.product_name as product_4_22_, menswear0_.product_type as product_5_22_ from hibernate5_mens_wears menswear0_
All MensWear Product :: 
MensWear [productId=1, productName=Active Chill, company=Reebok, productType=T-Shirts, price=2300]
MensWear [productId=2, productName=Sweet Animal, company=Reebok, productType=T-Shirts, price=1799]
MensWear [productId=3, productName=Addidas ZNE, company=Addidas, productType=Hoody, price=6999]
MensWear [productId=4, productName=Skull Cap, company=Reebok, productType=Cap, price=1499]



No comments:

Post a Comment