Best place to invoke java bean

I created a Edit Form. when the user clicks ‘Create’, it stores the entity into the database. I was wondering where is the best place to invoke my code. Should it be in the postCommit so I can get the UUID and do something with it or should be as a entityListener so that it would execute right after the object is created?

1 Like

It depends on what you are going to do with the entity.

In an entity listener, you can do something in the same transaction. So if your code throws an exception, everything will be rolled back, including the changes in the entity. This is often the main reason to use entity listeners - you can easily support invariants in your data model. Another benefit from entity listeners is that they are invoked regardless of the origin of entity changes - whether they came from a web client screen, REST API or a middleware service.

On the other hand, massive changes in the database or long processing should be performed in separate transactions. You can start a new transaction from the same entity listener, or by calling your service from the screen.

Encapsulating logic on middleware is a good idea because in this case the logic can be reused from different clients. Middleware beans can work with the database, client-tier beans cannot. But if you need a user interaction in your code, you have no choice but only calling it from the screen. Of course you can use a combination of client-tier and middleware beans.