开发者

Is it possible to impl database 'trigger' in java code? (hibernate + jpa + spring + mysql)

I am using mysql 5.5 DB, hibernate.4.0 as jpa provider to spring 3.0.5.

I have a user table and privilege table in my DB. Also I have some triggers in my DB. Those trigger implements some of our application's business logic.

For example, user john insert a record into table table_foo via my web application.

  1. The trigger BeforeInsertTableFoo will check the user's privilege. If user doesn't have the privilege, trigger will abort this operation.
  2. Also, if the operation is permitted, ano开发者_开发知识库ther trigger AfterInsertTableFoo will update some records in Table table_bar.

Is there any way that I can implement this logic as 'trigger' in java code? It seems like Jpa Event Listener and Hibernate Event can only do something like trigger but only in one table.

Surely I can use a java class to do the same thing. But I can't make sure that all the other developer, even myself, will use the correct java class to do db insertion or update, when the amount of business rules increased.

Thx in advance. andrew


Check the JPA's listener more carefully. You can make one listener for many entities / tables.

Just set a listener class like this:

public class MyListener {
@PrePersist void onPrePersist(Object entity ) {}
@PostPersist void onPostPersist(Object entity) {}
@PostLoad void onPostLoad(Object entity) {}
@PreUpdate void onPreUpdate(Object entity) {}
@PostUpdate void onPostUpdate(Object entity) {}
@PreRemove void onPreRemove(Object entity) {}
@PostRemove void onPostRemove(Object entity) {}

}

And then, for all the entities for which you want a call back or "trigger" ...

@Entity @EntityListeners(MyListener.class)
   public class Customer {
    }

I hope this helps.

-Alex


I found some links on google, which talks about Spring managed event listeners with JPA

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜