hibernate实体监听器

上学期学完spring的基本增删改查后,还曾有点小小的得意,感受本身也算知道很多的编程知识了,但这段时间的项目经验又一次次的教了本身作人,不断出现的新知识让本身应接不暇,知道的越多,未知的越多。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.
执行数据删除以前调用spa

@PostPersist

Executed after the entity manager persist operation is actually executed or cascaded. This call is invoked after the database INSERT is executed.
在执行数据插入以后调用hibernate

@PostRemove

Executed after the entity manager remove operation is actually executed or cascaded. This call is synchronous with the remove operation.
在执行数据删除以后调用code

@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总算有了一丁点清晰的认识,整体状态还算满意,感谢学长们的帮助。