Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
890 views
in Technique[技术] by (71.8m points)

jpa 2.0 - Triggers versus JPA Event

I'm doing a Web application using Spring 3.1.0.RELEASE, JSF 2.x, JPA 2 with Hibernate Provider, MySql 5.1.x. The application runs on Tomcat 7.X.

In my entities I have some date like last update date:

@Column(name = "last_update_date", insertable = false, updatable = false)
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdateDate;

For the moment I have a trigger that updates:

CREATE TRIGGER upd_site BEFORE UPDATE ON site
FOR EACH ROW SET NEW.last_update_date = CURRENT_TIMESTAMP();

It works fine, but I just notice that there is some callbacks methods in JPA http://www.objectdb.com/java/jpa/persistence/event

What is the best between JPA Events and the MySql's triggers ?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no best thing. A database trigger will update the last update date at every update of a row, whatever the way used to update the row (Hibernate, a JDBC query, or an update from your database admin tool). A JPA callback will only be invoked when the row is updated using JPA. You might want one or the other.

Another difference is that JPA is unaware of the trigger executed by the database. So if you update some field in your entity, and JPA flushed the change, the update date will be modified by the trigger, but the JPA entity will keep the old value of the update date in memory. So if this update date is displayed in the GUI after the update, the update date will be incorrect. You'll have to refresh the entity to get the latest update date.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...