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 @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 {@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="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 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 : 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 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/495980.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

WPF简介

WPF的全称是Windows Presentation Foundation&#xff0c;是微软新发布的Vista操作系统的三大核心开发库之一&#xff0c;其主要负责的是图形显示&#xff0c;所以叫Presentation&#xff08;呈现&#xff09;。 作为新的图形引擎&#xff0c;WPF是基于DirectX的&#xff0c;当…

简述 Python 的 Numpy、SciPy、Pandas、Matplotlib 的区别

From&#xff1a;https://www.jianshu.com/p/32cb09d84487 Numpy&#xff1a;基础的数学计算模块&#xff0c;以矩阵为主&#xff0c;纯数学。SciPy&#xff1a;基于Numpy&#xff0c;提供方法(函数库)直接计算结果&#xff0c;封装了一些高阶抽象和物理模型。比方说做个傅立叶…

干货|重磅发布:人工智能行业应用价值报告(PDF报告下载)

来源&#xff1a;机器人大讲堂报告下载&#xff1a;https://pan.baidu.com/s/1QEUOHqhQvxs9hEY6NLzPPg未来智能实验室是人工智能学家与科学院相关机构联合成立的人工智能&#xff0c;互联网和脑科学交叉研究机构。未来智能实验室的主要工作包括&#xff1a;建立AI智能系统智商评…

五年级上册分数计算机,分数计算题 五年级上册分数加减法计算题(100道)

题目&#xff1a;五年级上册分数加减法计算题(100道)有口算,也要有脱式计算解答&#xff1a;(1)6/147/14 (2)2/135/13 (3)6/159/15 (4)6/141/14(5)4/132/13 (6)2/152/15 (7)1/62/6 (8)3/148/14(9)3/144/14 (10)4/125/12 (11)4/93/9 (12)4/141/14(13)6/81/8 (14)8/113/11 (15)1/…

Spring Data JPA 从入门到精通~@PreUpdate异常场景分析

1、执行save()后&#xff0c;再次save()&#xff0c;PreUpdate不再触发 2、Transient字段的变更&#xff0c;不会触发PreUpdate方法 3、PreUpdate 不适用加密/解密场景 1、执行save()后&#xff0c;再次save()&#xff0c;PreUpdate不再触发 实体&#xff1a; Entity Entit…

ubuntu修改键盘映射

ubuntu修改键盘映射 通过xmodmap -pk 命令找到右shift键得keycode&#xff0c;打算将右shift映射到我笔记本的等号键去&#xff0c;因为笔记本上的等号键还具有加号键得功能&#xff0c;所以需要以下命令&#xff1a; xmodmap -e “keycode 62 equal plus” 62是右shift的keyc…

全球卫星导航 看中国“北斗”

来源&#xff1a;光明日报 作者&#xff1a;袁于飞2017年12月3日&#xff0c;第四届世界互联网大会世界互联网领先科技成果发布活动在浙江乌镇举行&#xff0c;中国卫星导航系统管理办公室主任冉承其介绍北斗卫星导航系统。新华社记者 孟鼎博摄3月30日&#xff0c;我国在西昌卫…

逻辑思维强的人适合学计算机不,逻辑思维强的人适合什么工作?

逻辑思维强的人适合什么工作?逻辑思维题内容&#xff1a;逻辑思维是人的理性认识阶段&#xff0c;人运用概念、判断、推理等思维类型反映事物本质与规律的认识过程。是人们将感性认识提升为理性认识的必要能力。那么逻辑思维强的人适合什么工作呢?逻辑性强的人适合做什么1.逻…

ADSL 拨号代理的搭建

From&#xff1a;崔庆才 - 轻松获得海量稳定代理&#xff01;ADSL拨号代理的搭建 我们尝试维护过一个代理池。代理池可以挑选出许多可用代理&#xff0c;但是常常其稳定性不高、响应速度慢&#xff0c;而且这些代理通常是公共代理&#xff0c;可能不止一人同时使用&#xff0c;…

用AlphaGo设计材料合成实验

来源&#xff1a;曾林的科学网博客AlphaGo下围棋连挫顶尖高手最终孤独求败的故事几乎家喻户晓。这也引发了大家对人工智能的能力的广泛思考。在科学研究领域&#xff0c;比如说合成实验设计&#xff0c;传统的做法不外乎是依靠经验不断的尝试。纵然会有一些热力学基本规律作为指…

Lambda 表达式详解~简化匿名内部类

本节将介绍如何使用Lambda表达式简化匿名内部类的书写&#xff0c;但Lambda表达式并不能取代所有的匿名内部类&#xff0c;只能用来取代函数接口&#xff08;Functional Interface&#xff09;的简写。先别在乎细节&#xff0c;看几个例子再说。 例子1&#xff1a;无参函数的简…

app store 服务器维护,AppStore无法连接怎么办?几个小方法教你解决问题

原标题&#xff1a;AppStore无法连接怎么办&#xff1f;几个小方法教你解决问题苹果用户都知道&#xff0c;AppStore我们下载应用的地方&#xff0c;无论是自带软件还是第三方软件都能在这里找到。但是有时候我们会遇上AppStore无法理解的问题&#xff01;简单来说&#xff0c;…

Python Twisted 介绍

Python Twisted介绍&#xff1a;http://blog.csdn.net/hanhuili/article/details/9389433 原文链接&#xff1a;http://www.aosabook.org/en/twisted.html 作者&#xff1a;Jessica McKellar Twisted 是用 Python 实现的 基于事件驱动 的 网络引擎框架&#xff0c;即一个 网络…

Microsoft OLE DB Provider for ODBC Drivers 错误 '80004005'

数据库用的是access&#xff0c;症状是 首页&#xff0c;列表页可以显示&#xff0c;但是内容页无显示 错误如下&#xff1a; Microsoft OLE DB Provider for ODBC Drivers 错误 80004005 readnews.asp 23行 我打开目录 找到readnews.aspx 页面发现&#xff0c;原来23行是一条:…

基于互联网大脑架构的阿里巴巴未来趋势分析【系列2】

作者 刘锋 《互联网进化论》作者&#xff0c;计算机博士前言在计算机科学中&#xff0c;计算机网络是指将地理位置不同的具有独立功能的多台计算机及其外部设备&#xff0c;通过通信线路连接起来&#xff0c;在网络操作系统&#xff0c;网络管理软件及网络通信协议的管理和协调…

Lambda 表达式详解~深入JVM实现原理

读过上一篇之后&#xff0c;相信对Lambda表达式的语法以及基本原理有了一定了解。对于编写代码&#xff0c;有这些知识已经够用。本文将进一步区分Lambda表达式和匿名内部类在JVM层面的区别&#xff0c;如果对这一部分不感兴趣&#xff0c;可以跳过。 经过第一篇的的介绍&…

从别的网站服务器获取数据,使用get()方法以GET方式从服务器获取数据

使用get()方法以GET方式从服务器获取数据我的个人资料$(function () {$("#btnShow").bind("click", function () {var $this $(this);? {$this.attr("disabled", "true");$("ul").append("我的名字叫&#xff1a;&qu…

关于Linq to DataSet

代码 privatePagedDataSource BindMethod(PagedDataSource pds, stringkeyword) { OthersTradeBo bo null; try{ bo newOthersTradeBo(); DataSet ds responseDataSet(bo); DataTable dt ds.Tables…

Twisted 入门 教程

GitHub 地址&#xff1a;https://github.com/likebeta/twisted-intro-cn/tree/master/zh https://github.com/luocheng/twisted-intro-cn 示例代码&#xff1a;https://github.com/jdavisp3/twisted-intro Twisted 与 异步编程入门 系列&#xff08; 英文 &#x…

OpenAI详细解析:攻击者是如何使用「对抗样本」攻击机器学习的

原文来源&#xff1a;OpenAI作者&#xff1a; Ian Goodfellow、Nicolas Papernot、Sandy Huang、Yan Duan、Pieter Abbeel、Jack Clark.「雷克世界」编译&#xff1a;嗯~是阿童木呀、EVA导语&#xff1a;一般来说&#xff0c;对抗样本&#xff08;adversarial examples&#xf…