hibernate实体监听器

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值