如何在坚持使用 JPA 的同时将 PrimaryKey(使用序列生成)的值分配给另一个变量?

How to assign value of PrimaryKey(generated using sequence) to another variable while persisting with JPA?

我已经实现了一个自定义的基于序列的生成器,它可以生成一个实体的主键。我想在保留实体的同时将相同的值分配给另一个成员变量。无论如何,这可以做到吗?

您可以使用 @PostPersist 注释方法。为了简单起见,我只使用自动生成的 ID。

@Entity
@Table(name = "PERSON")
class Person {

    @Id
    @GeneratedValue
    private Long id;

    private Long idDup;

    // Getters and setters removed for brevity

    @PostPersist
    public void perPersist() {
        this.idDup = id;
    }
}

来自文档:

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

请注意,@PostPersist 是一个 JPA 注释,因此适用于所有提供程序。