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



  


      

 

No comments:

Post a Comment