700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Spring Data JPA 从入门到精通~@EntityListeners注解示例

Spring Data JPA 从入门到精通~@EntityListeners注解示例

时间:2021-06-19 03:11:52

相关推荐

Spring Data JPA 从入门到精通~@EntityListeners注解示例

被@Prepersist注解的方法 ,完成save之前的操作。

被@Preupdate注解的方法 ,完成update之前的操作。

被@PreRemove注解的方法 ,完成remove之前的操作。

被@Postpersist注解的方法 ,完成save之后的操作。

被@Postupdate注解的方法 ,完成update之后的操作。

被@PostRemovet注解的方法 ,完成remove之后的操作。

This page will provide JPA @EntityListeners example with callbacks @PrePersist, @PostPersist, @PostLoad, @PreUpdate, @PostUpdate, @PreRemove, @PostRemove. JPA@EntityListenersis 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 JPAEntityManagerto interact with database.

JPA @EntityListeners

@EntityListenersannotation 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 typevoidand acceptone argument.

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

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

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

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

@PostUpdate: It is called after updating data.

@PreRemove: The method annotated with@PreRemovein listener bean class is called before removing data by using entity managerremove()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 {@PrePersistpublic void userPrePersist(User ob) {System.out.println("Listening User Pre Persist : " + ob.getName());}@PostPersistpublic void userPostPersist(User ob) {System.out.println("Listening User Post Persist : " + ob.getName());}@PostLoadpublic void userPostLoad(User ob) {System.out.println("Listening User Post Load : " + ob.getName());}@PreUpdatepublic void userPreUpdate(User ob) {System.out.println("Listening User Pre Update : " + ob.getName());}@PostUpdatepublic void userPostUpdate(User ob) {System.out.println("Listening User Post Update : " + ob.getName());}@PreRemovepublic void userPreRemove(User ob) {System.out.println("Listening User Pre Remove : " + ob.getName());}@PostRemovepublic 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="/xml/ns/persistence"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/persistence /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 ofEntityManager.

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 userUser user = new User(1, "Mahesh");entityManager.persist(user);entityManager.getTransaction().commit();//refresh userentityManager.refresh(user);//update userentityManager.getTransaction().begin();user.setName("Krishna");entityManager.getTransaction().commit();//remove userentityManager.getTransaction().begin();entityManager.remove(user);entityManager.getTransaction().commit();entityManager.close();JPAUtility.close();}}

Find the output.

Listening User Pre Persist : MaheshListening User Post Persist : MaheshListening User Post Load : MaheshListening User Pre Update : KrishnaListening User Post Update : KrishnaListening User Pre Remove : KrishnaListening User Post Remove : Krishna

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。