开发者

Using Hibernate/JPA Event Listener to update one entity when other entities are updated

开发者 https://www.devze.com 2023-01-18 17:42 出处:网络
I have three entities in my system - one of which must be updated when fields on the other two are changed:

I have three entities in my system - one of which must be updated when fields on the other two are changed:

@Entity
public class Order {
    private String name;
    private Integer quantity;
    private String status;
}

@Entity
public class OrderLocation {
    private String status;
    private String desc;
}

@Entity 
public class OrderKey {
    private String generatedKey;
}

So after any field on Order or OrderLocation are changed, I have to regenerate the key (in code), then save it back to OrderKey.

I've been looking at EntityListeners to do this, but unsure of whether to use JPA, or Hibernate versions. I'd like to use annotations ideally.

Any guidanc开发者_运维知识库e would be much appreciated - thanks in advance.


I really disapprove such a solution. In the project i'm working in, we use special handlers that do all the processing. The handlers have to know which entities must be updated in case of changes. E.g. use an abstract layer that handles the updating to the database. In case there are changes to Order or OrderLocation then it handles the update of the OrderKey.

In case you use listeners you also might have some problems with loops. So I suggest to use handlers instead of listerners within the entities.

But in case you want to use such a mechanism maybe you should try @PrePersist and @PreUpdate in order to invoke a method that is able to handle changes to the entity.

0

精彩评论

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