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

jayanth :

I have implemented a customised sequence based generator which generates primary key of an entity. I want to assign same value to another member variable while persisting the entity. Is there anyway this can be done?

Prashant :

You can use a @PostPersist annotated method. To keep things simple, let me just use an auto generated 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;
    }
}

From the documentation:

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

Note that @PostPersist is a JPA annotation hence would work on all providers.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=387627&siteId=1