Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate event listeners for JPA callbacks

How can I enable the Hibernate event listeners, that handle JPA callbacks?

Currently I am using using Hibernate 4 with SessionFactory configuration, but JPA callbacks are not running properly, when I persist an object.

Any suggestion are most welcome.

Source code

Temp Entity class:

package com.esp.entity;

import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.PostLoad;
import javax.persistence.Table;

import com.esp.aaa.TempVal;

@Entity
@EntityListeners(value=TempVal.class)
@Table(name="TEMP")
public class Temp {
    private int id;
    private String name;
    private String email;
    private int roll;

    @Id @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public int getRoll() {
        return roll;
    }
    public void setRoll(int roll) {
        this.roll = roll;
    }
    @PostLoad
    public void load(){
        System.out.println("post load called here");
    }
}

TempVal class:

package com.esp.aaa;

import javax.persistence.PrePersist;

public class TempVal {
    @PrePersist
    public void validate(Object temp){
        System.out.println("Object will persist now");
    }
}

MainClass class:

package com.esp.aaa;

import org.hibernate.Session;
import com.esp.entity.Temp;
import com.esp.utility.HibernateUtils;

public class MainClass {
    public static void main(String args[]) {
        HibernateUtils.createSessionFactory();
        Session session=HibernateUtils.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Temp temp=new Temp();

        temp.setEmail("[email protected]");
        temp.setName("Lucky");
        temp.setRoll(1112);

        session.save(temp);
        System.out.println("Object persist successfully");

        session.getTransaction().commit();
        HibernateUtils.shutdown();
    }
}

The Hibernate configuration:

<hibernate-configuration>
    <session-factory>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.current_session_context_class">thread</property>

        <mapping class="com.esp.entity.Temp"/>
    </session-factory>
</hibernate-configuration>

Program output

The program output is the following:

Hibernate: insert into TEMP (email, name, roll) values (?, ?, ?)
Object persist successfully

The expected output would be:

Object will persist now
Hibernate: insert into TEMP (email, name, roll) values (?, ?, ?)
Object persist successfully
like image 359
dom Avatar asked Feb 05 '15 09:02

dom


People also ask

What is @PrePersist in JPA?

JPA specifies seven optional lifecycle events that are called: before persist is called for a new entity – @PrePersist. after persist is called for a new entity – @PostPersist. before an entity is removed – @PreRemove. after an entity has been deleted – @PostRemove.

What is EntityListeners?

Annotation Type EntityListenersSpecifies the callback listener classes to be used for an entity or mapped superclass. This annotation may be applied to an entity class or mapped superclass. Since: Java Persistence 1.0.

What is JPA callback?

JPA includes a variety of callbacks methods for monitoring changes in the lifecycle of your persistent objects. These callbacks can be defined on the persistent classes themselves and on non-persistent listener classes.

What is @PrePersist in hibernate?

The @PrePersist and @PreUpdate annotations are JPA annotations introduced in JPA 1.0. Both annotations are used to configure callbacks that are triggered on specific entity lifecycle events. The @PrePersist annotation is used to configure a callback for pre-persist(pre-insert) events of the entity.


2 Answers

This question basically asked the same.

So it turns out, that these JPA entity listener annotations are only working when you are using EntityManager in Hibernate (which is understandable). So if you want to use these annotations, you should ditch SessionFactory, and use the JPA-complaint EntityManager or EntityManagerFactory.

I also recommend this approach, because if you are trying to use JPA annotations, it is logical to go for a pure JPA solution, without tying yourself to a Hibernate-specific solution - i.e. SessionFactory.

like image 57
meskobalazs Avatar answered Sep 30 '22 20:09

meskobalazs


Add a file named org.hibernate.integrator.spi.Integrator containing a single line

org.hibernate.jpa.event.spi.JpaIntegrator

in your META-INF/services folder. This will enable JPA lifecycle annotations including @EntityListeners for sessionFactory based configurations.

like image 42
Martin Petrus Avatar answered Sep 30 '22 20:09

Martin Petrus