JPA Derived Column value based on Identity column

后端 未结 3 1054
一个人的身影
一个人的身影 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:45

    You can create an interceptor for this requirement, see below example:

    Let's say you have an entity called Student with properties id (acts as an identifier) and foo.

    @Entity
    @Table(name = "test_student")
    public class Student {
        @Id
        @GeneratedValue
        private int id;
        private String foo;
        // Setters & Getters
    }
    

    Now you can create an interceptor that extends Empty Interceptor of hibernate and overrides the onSave method that sets the foo property with value as :{id} like this:

    import java.io.Serializable;
    import org.hibernate.CallbackException;
    import org.hibernate.EmptyInterceptor;
    import org.hibernate.type.Type;
    
    public class MyInterceptor extends EmptyInterceptor {
    
        public boolean onSave(Object entity, Serializable id, Object[] state,
                String[] propertyNames, Type[] types) throws CallbackException {
            System.out.println("Entered onSave : class - " + entity.getClass());
            if (entity instanceof Student) {
                Student s = (Student) entity;
                System.out.println("class:" + entity.getClass() + " , id: "+s.getId());
                s.setFoo(":"+id);
            }
            return false;
    
        }
    }
    

    Now you need to tell hibernate to use this interceptor like this:

    Configuration configuration = new Configuration().setInterceptor( new LogInterceptor() );
    configuration.configure();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-16 12:50

    The best solution is to simply compute the Column value upon loading, using @Formula:

    @Formula(value="':'||id||':'")
    private String foo;
    
    0 讨论(0)
提交回复
热议问题