Home  >  JPA

JPA @EntityListeners Example with Callbacks @PrePersist, @PostPersist, @PostLoad, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove

By Arvind Rai, February 04, 2016
This page will provide JPA @EntityListeners example with callbacks @PrePersist, @PostPersist, @PostLoad, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove. JPA @EntityListeners is used on entity or mapped superclass at class level. JPA provides callback methods for saving, fetching, updating and removing data from database. Here we will use JPA EntityManager to interact with database.

JPA @EntityListeners

@EntityListeners annotation specifies the callback listener classes . This annotation can be used for an entity or mapped superclass.
1. To configure single callback listener class, we can do as follows.
@EntityListeners(UserListener.class)
public class User {} 
2. To configure multiple callback listener classes, we can do as follows.
@EntityListeners({UserListener1.class, UserListener2.class})
public class User { } 

JPA Callbacks Method

JPA provides callback methods to listen saving, fetching, updating and removing data from database. These callback methods annotated in a listener bean class must have return type void and accept one argument.

@PrePersist: The method annotated with @PrePersist in listener bean class is called before persisting data by entity manager persist() method.

@PostPersist: The method annotated with @PostPersist is called after persisting data.

@PostLoad: The method annotated with @PostLoad is called after fetching data using entity manager find() method in persistence context or refreshing it with database by using refresh() method. If the entity instance is already loaded in persistence context, then calling of find() method will not call @PostLoad.

@PreUpdate: The method annotated with @PreUpdate in listener bean class is called before updating data.

@PostUpdate: It is called after updating data.

@PreRemove: The method annotated with @PreRemove in listener bean class is called before removing data by using entity manager remove() method.

@PostRemove: It is called after removing data.

Database Schema

For the demo we are using a table with following schema created in MySQL.
Table: user
CREATE TABLE `user` (
	`id` INT(11) NOT NULL,
	`name` VARCHAR(255) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 

Gradle File

Find the gradle file.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'HibernateJPA'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.hibernate:hibernate-entitymanager:5.0.7.Final'
    compile 'mysql:mysql-connector-java:5.1.31'
}   

Create Listener Class

Find the listener class which consist callback methods annotated with @PrePersist, @PostPersist, @PostLoad, @PreUpdate, @PostUpdate, @PreRemove and @PostRemove.
UserListener.java
package com.concretepage;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
public class UserListener {
	@PrePersist
	public void userPrePersist(User ob) {
		System.out.println("Listening User Pre Persist : " + ob.getName());
	}
	@PostPersist
	public void userPostPersist(User ob) {
		System.out.println("Listening User Post Persist : " + ob.getName());
	}
	@PostLoad
	public void userPostLoad(User ob) {
		System.out.println("Listening User Post Load : " + ob.getName());
	}	
	@PreUpdate
	public void userPreUpdate(User ob) {
		System.out.println("Listening User Pre Update : " + ob.getName());
	}
	@PostUpdate
	public void userPostUpdate(User ob) {
		System.out.println("Listening User Post Update : " + ob.getName());
	}
	@PreRemove
	public void userPreRemove(User ob) {
		System.out.println("Listening User Pre Remove : " + ob.getName());
	}
	@PostRemove
	public void userPostRemove(User ob) {
		System.out.println("Listening User Post Remove : " + ob.getName());
	}
} 

Create Entity annotated with @EntityListeners

Now find the entity annotated with @EntityListeners.
User.java
package com.concretepage;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@EntityListeners(UserListener.class)
@Table(name="user")
public class User {
	@Id
	@Column(name="id")
	private int id;
	@Column(name="name")
	private String name;
	public User() {}
	public User(int id, String name) {
		this.id = id;
		this.name = name;
	}
	public int getId() {
		return id;
	}	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
} 

persistence.xml

Find the persistence.xml file.
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence 
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="com.concretepage">
        <description>JPA Demo</description>
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/concretepage"/>
            <property name="javax.persistence.jdbc.user" value="root"/>
            <property name="javax.persistence.jdbc.password" value=""/>
        </properties>
    </persistence-unit>
</persistence> 

Run Application

First find the JPA utility singleton class that will provide the instance of EntityManager.
JPAUtility.java
package com.concretepage;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class JPAUtility {
 	private static final EntityManagerFactory emFactory;
	static {
		   emFactory = Persistence.createEntityManagerFactory("com.concretepage");
	}
	public static EntityManager getEntityManager(){
		return emFactory.createEntityManager();
	}
	public static void close(){
		emFactory.close();
	}
} 
Find the class to test the application.
JPAListenerDemo.java
package com.concretepage;
import javax.persistence.EntityManager;
public class JPAListenerDemo {
	public static void main(String[] args) {
		EntityManager entityManager = JPAUtility.getEntityManager();	
		entityManager.getTransaction().begin();
		//persist user
		User user = new User(1, "Mahesh");
		entityManager.persist(user);
		entityManager.getTransaction().commit();
		//refresh user
		entityManager.refresh(user);
		//update user
		entityManager.getTransaction().begin();				
		user.setName("Krishna");
		entityManager.getTransaction().commit();
		//remove user
		entityManager.getTransaction().begin();				
		entityManager.remove(user);
		entityManager.getTransaction().commit();		
		entityManager.close();
		JPAUtility.close();		
	}
} 
Find the output.
Listening User Pre Persist : Mahesh
Listening User Post Persist : Mahesh
Listening User Post Load : Mahesh
Listening User Pre Update : Krishna
Listening User Post Update : Krishna
Listening User Pre Remove : Krishna
Listening User Post Remove : Krishna 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS








Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us