Search code examples
javahibernatejpahibernate-mapping

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


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?


Solution

  • 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.