Triggers vs. JPA @PrePersist for creation and update timestamps pros and cons

不问归期 提交于 2019-12-03 07:32:11

Have to do a select after the insert and update to read the values that the triggers put into place.

You can use INSERT ... RETURNING or UPDATE ... RETURNING to retrieve the values that were changed by the trigger, so there is no need to do another SELECT.

Apart from that, I'd say it depends on your environment. If the application is mission critical and will fail miserably if those columns aren't maintained correctly, then I'd stick with the triggers.

If this is only for convenience in the front end (and it can handle conflicts due to incorrect values gracefully), then the JPA approach is probably easier to maintain.

I'm currently using Option A (with all your frameworks and PostgreSQL as well) in the following manner:

@Column(insertable = false, updatable = false, nullable = false, columnDefinition = "timestamp without time zone default CURRENT_TIMESTAMP")
@Generated(GenerationTime.INSERT)
public Date getCreatedIn() {
    return createdIn;
}

If you use the columnDefinition as written in the code you won't have to select the object again neither write any code to set the date on your objects. I've never used the JPA callbacks other than to connect Envers framework but I can say it looks too much effort only to set the date on specific objects.

Danger of clock skew in the cluster

I'd say not to worry about it. It can fail in the cluster just like it could fail in the database. In a proper production environment, you'd have your own NTP servers, and your cluster would sync with that.

I usually prefer to keep everything in Java, as a centralized place for "logic" is desirable (for me). Placing logic in triggers is acceptable if you have non-Java applications consuming it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!