如何知道运行时POJO的ID(@GeneratedValue) [英] How to know the ID (@GeneratedValue) of a POJO at runtime

查看:109
本文介绍了如何知道运行时POJO的ID(@GeneratedValue)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单填写POJO,名为 Father 。在它里面,我有一个 FotoFather 字段。

I have a form to fill a POJO called Father. Inside it, I have a FotoFather field.

当我保存一个新的父亲时,我自动保存对象FotoFather(使用Hibernate ORM模式)。

When I save a new Father, I save automatically the object FotoFather (with Hibernate ORM pattern).

FotoFather.fotoNaturalUrl 必须填充 Father.id 的值,这里是问题!

FotoFather.fotoNaturalUrl must be filled with the value of Father.id and here is the problem!

当我在db上保存 Father 时,当然我还没有 Father.id 值填充 FotoFather.fotoNaturalUrl 。如何解决这个问题?

When i'm saving Father on the db, of course I still haven't Father.id value to fill FotoFather.fotoNaturalUrl. How can I solve this problem?

谢谢

@Entity
@Table(name = "father")
public class Father implements Serializable{    
    ...
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    ...
    @OneToOne(targetEntity = FotoFather.class, fetch = FetchType.EAGER)
    @JoinColumn(name = "fotoFather", referencedColumnName = "id")
    @Cascade(CascadeType.ALL)
    private FotoFather fotoFather;
}

FotoFather.class

FotoFather.class

@Entity
@Table(name = "foto_father")
public class FotoFather.class{

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    ...
    @Column(name = "foto_natural_url")
    private String fotoNaturalUrl;
    ...
}


推荐答案

我想你可以在你的父类注册一个 @PostPersist 回调。如JPA规范所示:

I think you can do be registering an @PostPersist callback on your Father class. As the JPA spec notes:


在实体被持久化之后,为
实体调用PostPersist和PostRemove回调方法或移除。这些
回调也将在这些
操作级联的所有实体上被调用。 PostPersist和PostRemove方法将
分别在数据库插入和删除操作
后调用。这些数据库操作可以在
持久化,合并或删除操作被调用之后直接发生,或者它们可以在冲洗操作发生之后直接发生
(其可以是
结束交易)。 生成的主键值为
,可在PostPersist方法中使用。

public class Father(){

    @PostPersist
    public void updateFotoFather(){
        fotofather.setNaturalUrl("/xyz/" + id);
    }
}

这篇关于如何知道运行时POJO的ID(@GeneratedValue)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆