如何使用JPA回调?

栏目: Java · 发布时间: 6年前

内容简介:当您需要将自己的操作方法绑定到某个实体生命周期事件时,请不要重新发明轮子。只需依靠内置的JPA回调。本应用是启用JPA回调(Pre/ PostPersist,Pre/ PostUpdate,Pre/ PostRemove,和PostLoad)的示例。第一步:在实体中,编写回调方法并使用正确的注释:

当您需要将自己的操作方法绑定到某个实体生命周期事件时,请不要重新发明轮子。只需依靠内置的JPA回调。

本应用是启用JPA回调(Pre/ PostPersist,Pre/ PostUpdate,Pre/ PostRemove,和PostLoad)的示例。

第一步:在实体中,编写回调方法并使用正确的注释:

@Entity
<b>public</b> <b>class</b> User implements Serializable {

    <b>private</b> <b>static</b> <b>final</b> Logger logger = 
            Logger.getLogger(User.<b>class</b>.getName());
        
    <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    <b>private</b> Long id;

    <b>private</b> String name;
    <b>private</b> String city;
    <b>private</b> <b>int</b> age;
    
    @PrePersist
    <b>public</b> <b>void</b> prePersist() {
        logger.info(<font>"@PrePersist callback ..."</font><font>);
    }       
    
    @PreUpdate
    <b>public</b> <b>void</b> preUpdate() {
        logger.info(</font><font>"@PreUpdate callback ..."</font><font>);
    }
    
    @PreRemove
    <b>public</b> <b>void</b> preRemove() {
        logger.info(</font><font>"@PreRemove callback ..."</font><font>);
    }
    
    @PostLoad
    <b>public</b> <b>void</b> postLoad() {
        logger.info(</font><font>"@PostLoad callback ..."</font><font>);
    }
    
    @PostPersist
    <b>public</b> <b>void</b> postPersist() {
        logger.info(</font><font>"@PostPersist callback ..."</font><font>);
    }
    
    @PostUpdate
    <b>public</b> <b>void</b> postUpdate() {
        logger.info(</font><font>"@PostUpdate callback ..."</font><font>);
    }
    
    @PostRemove
    <b>public</b> <b>void</b> postRemove() {
        logger.info(</font><font>"@PostRemove callback ..."</font><font>);
    }
</font>

注意:在bean类上注释的回调方法必须返回void并且不带参数,比如@PrePersist 到@PostRemove

源代码可以在 这里 找到


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Tales from Facebook

Tales from Facebook

Daniel Miller / Polity Press / 2011-4-1 / GBP 55.00

Facebook is now used by nearly 500 million people throughout the world, many of whom spend several hours a day on this site. Once the preserve of youth, the largest increase in usage today is amongst ......一起来看看 《Tales from Facebook》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

在线进制转换器
在线进制转换器

各进制数互转换器

随机密码生成器
随机密码生成器

多种字符组合密码