views:

153

answers:

1

I want some of mycoulmns in the JPA entity to take values from database during inserts/updates, i.e from Oracle sys_context, I believe JPA temporal annotation includes database generated timestamps during insert/updates, Is there any way I could create a custom annotation somewhat simailar to this or provide some default values during inserts/updates, can someone give few pointers if you faced this situation.

+1  A: 

I want some of mycoulmns in the JPA entity to take values from database during inserts/updates

Configure the @Column to be not insertable and updatable and annotate the field with @Generated (Hibernate specific annotation). By doing so, Hibernate will fetch the value from the database after an insert, update. From the Reference Documentation:

2.4.3.5. Generated properties

Some properties are generated at insert or update time by your database. Hibernate can deal with such properties and triggers a subsequent select to read these properties.

@Entity
public class Antenna {
    @Id public Integer id;
    @Generated(GenerationTime.ALWAYS) 
    @Column(insertable = false, updatable = false)
    public String longitude;

    @Generated(GenerationTime.INSERT) @Column(insertable = false)
    public String latitude;
}

Annotate your property as @Generated You have to make sure your insertability or updatability does not conflict with the generation strategy you have chosen. When GenerationTime.INSERT is chosen, the property must not contains insertable columns, when GenerationTime.ALWAYS is chosen, the property must not contains insertable nor updatable columns.

@Version properties cannot be @Generated(INSERT) by design, it has to be either NEVER or ALWAYS.

Pascal Thivent