Friday, 4 September 2020

HowTo Use Event Listener in Hibernate 5

How To Use Event Listener in Hibernate 5 


Hibernate listener is used to perform an additional modification in during when Hibernate perform various operation on object like save,update,load,evict,refresh etc  for these event you can create a listener class then can execute when these event is occur in your application 

For this application I have use two listener 


Save Listener : Invoke when an Object is Save to database when calling session.save() method .

package in.jk.hibernate5.event.listener.use;

import org.hibernate.HibernateException;
import org.hibernate.event.spi.SaveOrUpdateEvent;
import org.hibernate.event.spi.SaveOrUpdateEventListener;

public class EmployeeSaveListener implements SaveOrUpdateEventListener {

@Override
public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {

System.out.println("Employee :: Save Lisnter Invoke :: ");

Object object = event.getEntity();
if (object instanceof Employee) {
Employee employee = (Employee) object;
System.out.println("Employee at Save Listener Before Save ::  " + employee);
System.out.println();

}

}

}

Load Listener :  Invoke when an Object is load from  database when calling session.load() method .

package in.jk.hibernate5.event.listener.use;

import org.hibernate.HibernateException;
import org.hibernate.event.spi.LoadEvent;
import org.hibernate.event.spi.LoadEventListener;

public class EmployeeLoadListener implements LoadEventListener {

@Override
public void onLoad(LoadEvent event, LoadType loadType) throws HibernateException {

System.out.println("Employee :: Load Listener  Invoke :: ");

Object object = event.getResult();
if (object instanceof Employee) {
Employee employee = (Employee) object;
System.out.println("Employee  At Load Listener ::   " + employee);

}

System.out.println("Employee :: Load Listener Execution End ::");

}

}


Listener Integrator : Listener Integrator used registered listener  to hibernate Service Registry .

package in.jk.hibernate5.event.listener.use;

import org.hibernate.boot.Metadata;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.integrator.spi.Integrator;
import org.hibernate.service.spi.SessionFactoryServiceRegistry;

public class HibernateEventListnerIntergarator implements Integrator {

@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory,
SessionFactoryServiceRegistry serviceRegistry) {

EventListenerRegistry eventListenerRegistry =serviceRegistry
               .getSe rvice(EventListenerRegistry.class);
eventListenerRegistry.getEventListenerGroup(EventType.SAVE)
               .appendListener(new EmployeeSaveListener());
eventListenerRegistry.getEventListenerGroup(EventType.LOAD)
                .appendListener(new EmployeeLoadListener());

}

@Override
public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {

}

}

Employee.java 

package in.jk.hibernate5.event.listener.use;

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

@Entity
@Table(name="hibernate5_event_listener_employee")
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 + "]";
}

}

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() {

// Session Factory Service To Config and Integrate Hibernate Listener
BootstrapServiceRegistry bootstrapServiceRegistry = new
BootstrapServiceRegistryBuilder()
.applyIntegrator(new HibernateEventListnerIntergarator()).build();
StandardServiceRegistryBuilder serviceRegistryBuilder = new
StandardServiceRegistryBuilder(bootstrapServiceRegistry);

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 Listener
metadataSources.addAnnotatedClass(in.jk.hibernate5.event.listener.use.Employee.class);

                Metadata metadata = metadataSources.getMetadataBuilder().build();
               sessionFactory = metadata.getSessionFactoryBuilder().build();
               return sessionFactory;

}

}


Hibernate5EventListenerApplication.java

package in.jk.hibernate5.event.listener.use;

import org.hibernate.Session;
import org.hibernate.Transaction;

import in.jk.hibernate5.HibernateUtils;

public class Hibernate5EventListenerApplication {

public static void main(String[] args) {

Session session = HibernateUtils.buildSessionFactory().openSession();
Transaction transaction = session.beginTransaction();

Employee employee = new Employee();
employee.setEmpId(10);
employee.setName("J K");
employee.setCompany("Google");
session.save(employee);

transaction.commit();

System.out.println("Employee Save Succussfully ..");
System.out.println();

Transaction transaction1 = session.beginTransaction();

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

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

transaction1.commit();
session.close();

}

}

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>

Output in Console 

----------------------

Employee :: Save Lisnter Invoke :: 

Employee at Save Listener Before Save ::  Employee [empId=10, name=J K, company=Google]

Hibernate: insert into hibernate5_event_listener_employee (company, name, emp_id) values (?, ?, ?)
Employee Save Succussfully ..

Hibernate: select employee0_.emp_id as emp_id1_13_0_, employee0_.company as company2_13_0_, employee0_.name as name3_13_0_ from hibernate5_event_listener_employee employee0_ where employee0_.emp_id=?
Employee :: Load Listener  Invoke :: 
Employee  At Load Listener ::   Employee [empId=1, name=J K, company=Google]
Employee :: Load Listener Execution End ::
Employee :: Employee [empId=1, name=J K, company=Google]


 

No comments:

Post a Comment