JPA Derived Column value based on Identity column

后端 未结 3 1056
一个人的身影
一个人的身影 2021-01-16 11:55

JPA 2.0 (Hibernate 4.2.4.Final/Spring 3.2.8.Release) / Mysql 5.6

For a managed entity E w/ auto-generated primary key e.g.

...
@Id
@GeneratedValue
pr         


        
3条回答
  •  不知归路
    2021-01-16 12:49

    You can use a JPA PostPersist Event Listener to handle this.

    @Id
    @GeneratedValue
    private int id;
    
    @Column
    private String foo;
    
    @PostPersist
    public void onSave(){
        foo = ":" + id + ":";
    }
    

    From the JPA 2 specification:

    The PostPersist and PostRemove callback methods are invoked for an entity after the entity has been made persistent or removed. These callbacks will also be invoked on all entities to which these operations are cascaded. The PostPersist and PostRemove methods will be invoked after the database insert and delete operations respectively. These database operations may occur directly after the persist, merge, or remove operations have been invoked or they may occur directly after a flush operation has occurred (which may be at the end of the transaction). Generated primary key values are available in the PostPersist method.

提交回复
热议问题