博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hibernate实体监听器
阅读量:7218 次
发布时间:2019-06-29

本文共 1824 字,大约阅读时间需要 6 分钟。

上学期学完spring的基本增删改查后,还曾有点小小的得意,感觉自己也算知道不少的编程知识了,但这段时间的项目经验又一次次的教了自己做人,不断出现的新知识让自己目不暇接,知道的越多,未知的越多。

clipboard.png

也算进入了学习的另一个阶段:

知道自己不知道

感慨完了,该进入正题了,本周有一个需求,spring sercurity要求在保存密码的时候密码必须加密,学长开始写的时候是在setter密码的时候调用加密方法,不够优雅,就让我把这个方法提出来,换用监听器,当监听的user保存时就自动加密其密码,由于当时只知道拦截器,于是就去找了一篇拦截器的教程,发现写出来感觉相当不合适,就问学长,果然我理解错了意思,是用一个叫实体监听器(Entity Listeners)的东西。

Entity Listener

顾名思义,它可以监听实体的某些行为,并进行一部分操作。

Hibernate支持的回调注解

@PrePersist

Executed before the entity manager persist operation is actually executed or cascaded. This call is synchronous with the persist operation.

在数据持久化到数据库之前执行

@PreRemove

Executed before the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.

执行数据删除之前调用

@PostPersist

Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.

在执行数据插入之后调用

@PostRemove

Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.

在执行数据删除之后调用

@PreUpdate

Executed before the database UPDATE operation.

在执行数据更新之前调用

@PostUpdate

Executed after the database UPDATE operation.

在执行数据更新之后调用

@PostLoad

Executed after an entity has been loaded into the current persistence context or an entity has been refreshed.

在数据从数据库加载并且赋值到当前对象后调用

用法

首先,先定义一个操作用的类,并在其中写下你要用的方法,比如下面的方法就代表在用户持久化和更新的时候执行(只需注解就好,不用继承其他类)。

clipboard.png

然后在实体上声明,就完工了,相当简单。

clipboard.png

对于上面的代码,初学者可能会对这一段有疑惑

PasswordEncoder passwordEncoder = ContextConfig.getContext().getBean(PasswordEncoder.class);

我开始也不明白,还是学长给我讲解的,这是获取PasswordEncoder的对象,学长给我讲了讲才大概明白了hibernate和spring是两个系统,spring管理的对象,hibernate注入不进来。如果不明白可以看看下面这个图。

spring的ioc

clipboard.png

这篇文章写得挺不错,有兴趣可以。

总结

实体监听器虽然只是一个很简单的功能,但却非常强大与实用,这段时间以来同时了解到hibernate和spring并不是一个东西,以前一直以为hibernate是spring的一个小功能,同时对spring总算有了一丁点清晰的认识,总体状态还算满意,感谢学长们的帮助。

转载地址:http://bxxym.baihongyu.com/

你可能感兴趣的文章
C++创建一个动态链接库工程
查看>>
(六)maven之本地仓库
查看>>
如何使用 SPICE client (virt-viewer) 来连接远程虚拟机桌面?
查看>>
CentOS7
查看>>
linux高编IO-------tmpnam和tmpfile临时文件
查看>>
微信的机器人开发
查看>>
从零开始学Java(二)基础概念——什么是"面向对象编程"?
查看>>
近期面试总结(2016.10)
查看>>
CodeForces 525D Arthur and Walls :只包含点和星的矩阵,需要将部分星变成点使满足点组成矩形 : dfs+思维...
查看>>
积累_前辈的推荐
查看>>
strcpy和memcpy的区别《转载》
查看>>
在windows平台下electron-builder实现前端程序的打包与自动更新
查看>>
DroidPilot V2.1 手写功能特别版
查看>>
COOKIE欺骗
查看>>
js 强转规范解读
查看>>
ACdream - 1735:输油管道
查看>>
golang 获取get参数
查看>>
服务器状态码
查看>>
非小型电子商务系统设计经验分享
查看>>
Video Target Tracking Based on Online Learning—深度学习在目标跟踪中的应用
查看>>