Sunday 6 September 2020

Use Of Hibernate various method


Use of Hibernate Session Interface methods in Hibernate 5


1.Persist Method :- 
Persist method used to insert an object . persist() method insert a transient object into database and assign persistent identifier to object. However, persist() method doesn't guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time.
Syntax :- public void persist(Object object);

2.Save Method :-
Save method used method used to insert one object . save() method insert a transient object into database and assign persistent identifier to object. save() return Serializable interface which can be cast to object identifier type value;

Syntax :- public Serializable save(Object object);

3.SaveOrUpdate Method:- 
SaveOrUpdate() method insert and update a transient and detached object in database for given object  into database and assign an identifier to object. if you try to save an object  with duplicate identifier then saveOrUpdate () method update this object.

Syntax :- public void saveOrUpdate(Object object);

4. Get Method :- 
Get Method is used to fetch an object from database . if object is not found in database it return null.
get() method always hit to database return fully initialized object . 

Syntax :- public T get(Class<T>entityType ,Serialazable objectId);

5. Load Method :- 
Load Method is used to fetch an object from database . if object is not found in database it return ObjectNotFoundException.load() method first search an object in cache then hit to database . load() method may return a proxy object instead of actual object proxy object is lazy initialized . proxy object may only initialized with identifier without other properties initialization.

Syntax :- public T load(Class<T>entityType ,Serialazable objectId);

6  ById Method :-
ById Method used to fetch object from database . 

IdentifierLoadAccess<MyObject> object = session.byId(Class<MyObject>);

IdentifierLoadAccess allow to specify  lock option and cacheMode  
Post post = session.byId( Post.class )
                   .with( new LockOptions( LockMode.OPTIMISTIC_FORCE_INCREMENT) )
                   .with( CacheMode.GET )
                   .load( objectId );

IdentifierLoadAccess  also provide getRefrence(objectId) method getting the refernce to proxy .

Post post = session.byId( Post.class )
                   .with( new LockOptions( LockMode.OPTIMISTIC_FORCE_INCREMENT) )
                   .with( CacheMode.GET )
                   .getRefrence(objectId);

So session.byId method more flexible then Standard get() and load() method 



7. Update Method :- 
Update Method used to update an object object . update() method can't update detached object if an object with same identifier found in session  then it throws  org.hibernate.NonUniqueObjectException .

8. Merge Method :- 
In Hibernate if you can't update detached  an object in session via update() method  if an object with same identifier already present in session  in that case  update() method  throws following exception org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session So in that case to  update an detached object hibernate provide the merger() method which merge the detached object changes with object present in current session .

Note :- If you want save the your modifications of object without knowing of state of session then use merge() method.

9. Delete Method :- 
Delete method used to delete an object from database state of given identifier .


10.Refresh Method :-
In Hibernate session if we update an object in session then object does not reelect it changes without calling of update method or committing current transaction(Dirty check update). so in that case hibernate provide session interface refresh() method . refresh () compare current session object value to database object and update the with new values . 
 
11.Flush Method :- 

Flush Method synchronized all object changes in session with database store object . 

12. Evict Method :- 
Evict Method remove a given object form current session(session cache) and after calling of evict on given object  if your try fetch it again then it execute a new request to database  which result into new SQL Query to database .

13. Clear Method :- Clear Method remove all object present i session cache .

14 .Close Method  :Close Method close the session .

15 . Open Session Method : 
Open Session method open a new session every time when it invoke . openSession() is not thread safe  it use int multi threaded environment

16 . Current Session Method :
SessionFactory.getCurrentSession() open a new session hibernate context  that managed by hibernate it have transaction scope. getCurrentSession() open a new session when first time is called .otherwise it return previous hibernate context open session. Session open by getCurrentSession() automatically flush and close when transaction is end .

17. Replicate() Method :- replicate() method Data is replicated in different Data store in different modes.

Bellow is  Source code for that illustrate working of hibernate method .

User.java

package in.jk.hibernate5.methods.use;

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

@Entity
@Table(name="hibernate5_method_use_user_master")
public class User {
@Id
@Column(name="user_id")
private int userId;
@Column(name="name")
private String name;
@Column(name="email_id")
private String emailId;
@Column(name="contact_number")
private String contactNumber;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getContactNumber() {
return contactNumber;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
@Override
public String toString() {
return "User [userId=" + userId + ", name=" + name + ", emailId=" + emailId + ", contactNumber=" + contactNumber
+ "]";
}

}


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 = 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);

// Hibernate Method Use
metadataSources.addAnnotatedClass(in.jk.hibernate5.methods.use.User.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>
</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>



HibernateMethodApplication.java 

package in.jk.hibernate5.methods.use;

import java.sql.Connection;
import java.sql.SQLException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.jdbc.Work;
HibernateMethodApplication 
import org.hibernate.SessionFactory;
import in.jk.hibernate5.HibernateUtils;
import in.jk.hibernate5.mergeandupdate.Employee;

public class HibernateMethodApplication {

private static SessionFactory sessionFactory;

public static void main(String[] args) {

sessionFactory = HibernateUtils.buildSessionFactory();

System.out.println("---------Hibernate Method Application ------\n");
HibernateMethodApplication.persistUser();
System.out.println("\n--------- Save Method  ------\n");
HibernateMethodApplication.saveUser();
System.out.println("\n--------- Save Or Update Method  ------\n");
HibernateMethodApplication.saveOrUpdateUser();
System.out.println("\n--------- Get Method  ------\n");
HibernateMethodApplication.getUser();
System.out.println("\n--------- Load Method  ------\n");
HibernateMethodApplication.loadUser();
System.out.println("\n--------- ById Method  ------\n");
HibernateMethodApplication.findUserById();
System.out.println("\n---------  Update Method  ------\n");
HibernateMethodApplication.update();
System.out.println("\n--------- Merge Method  ------\n");
HibernateMethodApplication.merge();
System.out.println("\n--------- Delete Method  ------\n");
HibernateMethodApplication.delete();
System.out.println("\n--------- refresh Method  ------\n");
HibernateMethodApplication.refresh();
System.out.println("\n--------- evictfresh Method  ------\n");
HibernateMethodApplication.evict();

}

/*
* session.persist() method save object in database for given object id if same
* object with duplicate id then it Throws an Exception ::
* org.hibernate.exception.ConstraintViolationException:
*/

private static void persistUser() {

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

User user = new User();
user.setUserId(1);
user.setName("John Johnson");
user.setEmailId("jk@mail.com");
user.setContactNumber("28046746546");
session.persist(user);
System.out.println("User Persist Succussfully ...");

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

}

/*
* session.save() method save object in database for given object id if same
* object with duplicate id then it Throws an Exception ::
* org.hibernate.exception.ConstraintViolationException:
*/

private static void saveUser() {

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

User user = new User();
user.setUserId(2);
user.setName("John Alison");
user.setEmailId("john@mail.com");
user.setContactNumber("28046746546");

int userId = (int) session.save(user);
System.out.println("User Save Succussfully with User Id " + userId);

session.save(user);

transaction.commit();
session.close();
}
/*
* session.saveOrUpdate() method save object in database for given object id if
* same object with duplicate id then it update the object
*/

private static void saveOrUpdateUser() {

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

User user = new User();
user.setUserId(3);
user.setName("Ikram");
user.setEmailId("ikram@mail.com");
user.setContactNumber("280467465445");

session.saveOrUpdate(user);
System.out.println("User Save Succussfully ...");
user.setName("J K ");
session.saveOrUpdate(user);
        System.out.println("User Updated Succussfully ...");

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

/*
* session.get() method return object for given object id if object not found in
* data base it return null;
*/
private static void getUser() {

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

User user1 = session.get(User.class, 1);

System.out.println("User by GET with Id 1 ::" + user1);

User user2 = session.get(User.class, 100);

System.out.println("User by GET with Id 100 ::" + user2);

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

/*
* session.load() method return object for given object id if object not found
* in data base it throw an Exception : org.hibernate.ObjectNotFoundException:
* No row with the given identifier exists: ;
*/
private static void loadUser() {

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

User user1 = session.load(User.class, 1);

System.out.println("User by Load with Id 1 ::" + user1);

try {
User user2 = session.load(User.class, 100);
System.out.println("User by Load with Id 100 ::" + user2);
} catch (Exception e) {
System.out.println("Error in find User :: " + e);
}

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

/*
* session.byId() method return object for given object id if object not found
* in data base it return null;
*/

private static void findUserById() {

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

User user1 = session.byId(User.class).load(1);

System.out.println("User by ById with Id 1 ::" + user1);

try {
User user2 = session.byId(User.class).load(100);
System.out.println("User by ById with Id 100 ::" + user2);
} catch (Exception e) {
System.out.println("Error in find User :: " + e);
}

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

private static void update() {

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

User user = session.get(User.class, 1);
user.setEmailId("johny@gmail.com");
session.update(user);
System.out.println("User :: 1 " + user);
transaction.commit();
session.close();

Session session2 = sessionFactory.openSession();
Transaction transaction1 = session2.beginTransaction();

user.setEmailId("john@gmail.com");
session2.update(user);

System.out.println("User Update with Email :: 2 " + user);

Employee emp3 = session2.get(Employee.class, 1);
System.out.println("Updated User :: 3 " + emp3);

transaction1.commit();
session2.close();

}

public static void merge() {

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

User user = session.get(User.class, 1);

System.out.println("User  :: 1 " + user);

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

Session session2 = sessionFactory.openSession();
Transaction transaction1 = session2.beginTransaction();

User user1 = session2.get(User.class, 1);

user.setEmailId("jk@gmail.com");

// session2.update(user); Error --> org.hibernate.NonUniqueObjectException: A
// different object with the same identifier value was already associated with
// the session

session2.merge(user);

System.out.println("User Merge :: 1 " + user1);

User user2 = session2.get(User.class, 1);
System.out.println("Updated User After Merge User :: 3 " + user2);

transaction1.commit();
session2.close();

}

private static void delete() {

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

User user1 = session.byId(User.class).load(1);
System.out.println("User 1 ::" + user1);

session.delete(user1);

System.out.println("Object Deleted Succussfully ...");

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

private static void refresh() {

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

User user1 = session.byId(User.class).load(3);
System.out.println("User 1 ::" + user1);

Work work = new Work() {

@Override
public void execute(Connection connection) throws SQLException {

PreparedStatement statement = connection
.prepareStatement("Update hibernate5_user_list set name=? where user_id=?");

statement.setString(1, "Johnson Legend");
statement.setInt(2, 3);
int count = statement.executeUpdate();
System.out.println("Update Count : " + count);

}
};
session.doWork(work);

session.refresh(user1);
System.out.println("User After Update  and Refresh ::" + user1);

System.out.println("Object Deleted Succussfully ...");

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

private static void evict() {

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

User user1 = session.byId(User.class).load(3);
System.out.println("User 1  :: I ::" + user1);

System.out.println("------------------Without Calling Evict method ----------------------------");

User user2 = session.byId(User.class).load(3);
System.out.println("User 1 :: II ::" + user2);

System.out.println("-----------------After Calling of Evict method-----------------------------");

session.evict(user1);
User user3 = session.byId(User.class).load(3);
System.out.println("User 1 :: III ::" + user3);

System.out.println("Object Deleted Succussfully ...");

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

}


 
Output in conolse ..
------------------------------------------

INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@27cbfddf] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table hibernate5_method_use_user_master (user_id int4 not null, contact_number varchar(255), email_id varchar(255), name varchar(255), primary key (user_id))
Sep 07, 2020 1:50:59 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
---------Hibernate Method Application ------

User Persist Succussfully ...
Hibernate: insert into hibernate5_method_use_user_master (contact_number, email_id, name, user_id) values (?, ?, ?, ?)

--------- Save Method  ------

User Save Succussfully with User Id 2
Hibernate: insert into hibernate5_method_use_user_master (contact_number, email_id, name, user_id) values (?, ?, ?, ?)

--------- Save Or Update Method  ------

Hibernate: select user_.user_id, user_.contact_number as contact_2_23_, user_.email_id as email_id3_23_, user_.name as name4_23_ from hibernate5_method_use_user_master user_ where user_.user_id=?
User Save Succussfully ...
User Updated Succussfully ...
Hibernate: insert into hibernate5_method_use_user_master (contact_number, email_id, name, user_id) values (?, ?, ?, ?)
Hibernate: update hibernate5_method_use_user_master set contact_number=?, email_id=?, name=? where user_id=?

--------- Get Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User by GET with Id 1 ::User [userId=1, name=John Johnson, emailId=jk@mail.com, contactNumber=28046746546]
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User by GET with Id 100 ::null

--------- Load Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User by Load with Id 1 ::User [userId=1, name=John Johnson, emailId=jk@mail.com, contactNumber=28046746546]
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
Error in find User :: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [in.jk.hibernate5.methods.use.User#100]

--------- ById Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User by ById with Id 1 ::User [userId=1, name=John Johnson, emailId=jk@mail.com, contactNumber=28046746546]
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User by ById with Id 100 ::null

---------  Update Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User :: 1 User [userId=1, name=John Johnson, emailId=johny@gmail.com, contactNumber=28046746546]
Hibernate: update hibernate5_method_use_user_master set contact_number=?, email_id=?, name=? where user_id=?
User Update with Email :: 2 User [userId=1, name=John Johnson, emailId=john@gmail.com, contactNumber=28046746546]
Hibernate: select employee0_.emp_id as emp_id1_16_0_, employee0_.company as company2_16_0_, employee0_.designation as designat3_16_0_, employee0_.name as name4_16_0_ from hibernate5_google_employee employee0_ where employee0_.emp_id=?
Updated User :: 3 Employee [empId=1, name=J K, company=Google, designation=Java Developer]
Hibernate: update hibernate5_method_use_user_master set contact_number=?, email_id=?, name=? where user_id=?

--------- Merge Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User  :: 1 User [userId=1, name=John Johnson, emailId=john@gmail.com, contactNumber=28046746546]
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User Merge :: 1 User [userId=1, name=John Johnson, emailId=jk@gmail.com, contactNumber=28046746546]
Updated User After Merge User :: 3 User [userId=1, name=John Johnson, emailId=jk@gmail.com, contactNumber=28046746546]
Hibernate: update hibernate5_method_use_user_master set contact_number=?, email_id=?, name=? where user_id=?

--------- Delete Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User 1 ::User [userId=1, name=John Johnson, emailId=jk@gmail.com, contactNumber=28046746546]
Object Deleted Succussfully ...
Hibernate: delete from hibernate5_method_use_user_master where user_id=?

--------- refresh Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User 1 ::User [userId=3, name=J K , emailId=ikram@mail.com, contactNumber=280467465445]
Update Count : 1
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User After Update  and Refresh ::User [userId=3, name=J K , emailId=ikram@mail.com, contactNumber=280467465445]
Object Deleted Succussfully ...

--------- evictfresh Method  ------

Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User 1  :: I ::User [userId=3, name=J K , emailId=ikram@mail.com, contactNumber=280467465445]
------------------Without Calling Evict method ----------------------------
User 1 :: II ::User [userId=3, name=J K , emailId=ikram@mail.com, contactNumber=280467465445]
-----------------After Calling of Evict method-----------------------------
Hibernate: select user0_.user_id as user_id1_23_0_, user0_.contact_number as contact_2_23_0_, user0_.email_id as email_id3_23_0_, user0_.name as name4_23_0_ from hibernate5_method_use_user_master user0_ where user0_.user_id=?
User 1 :: III ::User [userId=3, name=J K , emailId=ikram@mail.com, contactNumber=280467465445]
Object Deleted Succussfully ...



  


      

 

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]



Friday 4 September 2020

Second Level Cache Configuration in Hibernate 5


 Second Level Cache Configuration in Hibernate 5 


Caching is used to enhance the performance of application . Cache create an in memory storage location(memory buffer) to store recently used data item or objects . when hibernate first time fetch an object from database then hibernate store it in cache memory for future use . if same object require one more time in application then hibernate retrieved from cache memory and no database fetch required that's why it reduced the database query which exceed the performance of application.


Hibernate have three type of cache 

First Level Cache  : First level cache use by hibernate Session it by default enable .

Second Level Cache :Second level use by SessionFactory it require configuration . 
To enable second level cache hibernate require the cache provider vendor .
in our application we have used EHCache vendor implementation .

 EHCache : It can cache in memory or on disk and clustered caching and it
supports the optional Hibernate query result cache.

Second Level Query Cahche : In Hibernate we can fetch object from using hibernate method or using hibernate query language .
if you fetching object using HQL Query then create Query  by setting query cache able true .

Query<Employee> query = session.createQuery("FROM Employee" ,Employee.class); 
query.setCacheable(Boolean.TRUE);
List<Employee> employees =query.getResultList();
 
 

Maven Depedpendcy for EHCache vendor :

<!-- 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>

Add following properties in config 

// Second Level Cache Config
Environment.USE_SECOND_LEVEL_CACHE  =  Boolean.toString(Boolean.TRUE)
Environment.CACHE_REGION_FACTORY,   =  "org.hibernate.cache.ehcache.EhCacheRegionFactory"
Environment.CACHE_PROVIDER_CONFIG =   "net.sf.ehcache.hibernate.EhCacheProvider"

Hibernate Entity Class  
Add @Cacheable annotation at class . you can specify optional cache concurrency scheme by @Cache Annotation

Employee.java

package in.jk.hibernate5.second.level.cache;

import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

@Entity
@Table(name="hibernate5_second_level_cache_employee")
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Employee {
@Id
@Column(name = "emp_id")
private int empId;
@Column(name = "name")
    private String name;
@Column(name = "company")
    private String company;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", name=" + name + ", company=" + company + "]";
}
}

Hibernate Config class :

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.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Environment;
import in.jk.hibernate5.example.Employee;
import in.jk.hibernate5.onetoone.mapping.Address;
import in.jk.hibernate5.onetoone.mapping.User;

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 = 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");

// Second Level Cache Config
hibernateProperties.put(Environment.USE_SECOND_LEVEL_CACHE,         Boolean.toString(Boolean.TRUE));
hibernateProperties.put(Environment.USE_QUERY_CACHE, Boolean.toString(Boolean.TRUE));

hibernateProperties.put(Environment.CACHE_REGION_FACTORY, "org.hibernate.cache.ehcache.EhCacheRegionFactory");
hibernateProperties.put(Environment.CACHE_PROVIDER_CONFIG, "net.sf.ehcache.hibernate.EhCacheProvider");

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

      // Second Level Cache
metadataSources.addAnnotatedClass(in.jk.hibernate5.second.level.cache.Employee.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>


SecondLevelCachaeHibernate5Application .java

package in.jk.hibernate5.second.level.cache;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import in.jk.hibernate5.HibernateUtils;

public class SecondLevelCachaeHibernate5Application {

private static SessionFactory sessionFactory;

public static void main(String[] args) {

sessionFactory = HibernateUtils.buildSessionFactory();
SecondLevelCachaeHibernate5Application.addEmployee();
SecondLevelCachaeHibernate5Application.findEmployeeByCache();
SecondLevelCachaeHibernate5Application.findEmployeeByQueryCache();

}

private static void addEmployee() {
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();

Employee employee = new Employee();
employee.setEmpId(1);
employee.setName("J K");
employee.setCompany("Google");
//session.persist(employee);

transaction.commit();

session.close();

System.out.println("Employee Added ....");
}

private static void findEmployeeByCache() {
System.out.println("Hibernate Cache  :: ");

Session session = sessionFactory.openSession();

Transaction transaction1 = session.beginTransaction();

Employee emp = session.get(Employee.class, 1);

System.out.println("Employee :: 1 " + emp);

System.out.println("-------------------------------------------------");

Employee emp2 = session.get(Employee.class, 1);

System.out.println("Employee :: 2  " + emp2);

transaction1.commit();
session.close();
System.out.println("..............Session Close .........");
System.out.println();
Session session2 = sessionFactory.openSession();

Transaction transaction2 = session2.beginTransaction();

Employee emp3 = session2.get(Employee.class, 1);

System.out.println("Employee :: 3 " + emp3);

System.out.println("-------------------------------------------------");

Employee emp4 = session2.get(Employee.class, 1);

System.out.println("Employee :: 4  " + emp4);

transaction2.commit();
session2.close();
}
private static void findEmployeeByQueryCache() {
System.out.println("Hibernate Query Cache  :: ");


Session session = sessionFactory.openSession();

Transaction transaction1 = session.beginTransaction();

Query<Employee> query = session.createQuery("FROM Employee" ,Employee.class); 
query.setCacheable(Boolean.TRUE);
List<Employee> employees =query.getResultList();
employees.forEach(System.out::println);


System.out.println("-------------------------------------------------");

Query<Employee> query2 = session.createQuery("FROM Employee" ,Employee.class); 
query2.setCacheable(Boolean.TRUE);
List<Employee> employees2 =query2.getResultList();
employees2.forEach(System.out::println);
transaction1.commit();

session.close();

System.out.println("..............Session Close .........");
System.out.println();

Session session2 = sessionFactory.openSession();

Transaction transaction2 = session2.beginTransaction();

Query<Employee> query3 = session2.createQuery("FROM Employee" ,Employee.class); 
query3.setCacheable(Boolean.TRUE);
List<Employee> employees3 =query3.getResultList();
employees3.forEach(System.out::println);

System.out.println("-------------------------------------------------");

Query<Employee> query4 = session2.createQuery("FROM Employee" ,Employee.class); 
query4.setCacheable(Boolean.TRUE);
List<Employee> employees4 =query4.getResultList();
employees4.forEach(System.out::println);

transaction2.commit();

session2.close();

}

}



Ouput in Console  here ::
SQL Query execute only once  out of four call in rest case object return from cache even if we close the session .


Employee Added Succussfully ....
Fetching Object by Hibernate Cache  :: 
Hibernate: select employee0_.emp_id as emp_id1_26_0_, employee0_.company as company2_26_0_, employee0_.name as name3_26_0_ from hibernate5_second_level_cache_employee employee0_ where employee0_.emp_id=?
Employee :: 1 Employee [empId=1, name=J K, company=Google]
-------------------------------------------------
Employee :: 2  Employee [empId=1, name=J K, company=Google]
----------- Session Close ---------------

Here No SQL Query to Database Object return form Cache .
Employee :: 3  Employee [empId=1, name=J K, company=Google]
-------------------------------------------------
Employee :: 4  Employee [empId=1, name=J K, company=Google]
Hibernate Query Cache  :: 
Hibernate: select employee0_.emp_id as emp_id1_26_, employee0_.company as company2_26_, employee0_.name as name3_26_ from hibernate5_second_level_cache_employee employee0_
Employee [empId=1, name=J K, company=Google]
-------------------------------------------------
Employee [empId=1, name=J K, company=Google]
----------- Session Close ---------

Here No SQL Query to Database Object return form Cache .
Employee [empId=1, name=J K, company=Google]
-------------------------------------------------
Employee [empId=1, name=J K, company=Google]