开发者

Create a custom JPA temporal annotation

开发者 https://www.devze.com 2023-01-08 07:30 出处:网络
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 du

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, c开发者_Go百科an someone give few pointers if you faced this situation.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消