I have an Administrator entity that has a property called Type. Administrators can be complete or limited. I need to ensure that, no matter what happens, there is always at least one complete administrator in the entity store.
For deleting, persisting, and merging, this is not a problem, because I can add the check to the corresponding methods in the DAO. But, how do I run this check when an entity is updated? In JPA, there is not explicit method to update an entity (it happens automatically during flushing).
JPA life cycle handlers (@PreUpdate, @PostUpdate) won't help as you cannot load from the persistence store during their execution. It is for this reason that I suspect Hibernate event listeners and interceptors won't work either (can someone confirm this?).
Theoretically, I might be able to use validation to solve this need (at least for update). However, aside from the fact that it is very difficult to get access to the persistence context from the container-managed validators, it is really the wrong place to do this. This is a store-wide validation and should take place in the DAO.
One suggestion is that it should be check in code. That means every time I update an administrator, I have to remember to run this check:
Code:
administrator.setType(AdministratorType.LIMITED);
administratorRepository.verifyCompleteAdministratorCount();
or
Code:
if (administratorRepository.getCompleteAdministratorCount() > 1)
administrator.setType(AdministratorType.LIMITED);
But that is way to easy to screw up; especially if I am scripting against my API.
I have also looked into AOP and transaction events (Spring). But, in my stack, transactions are managed at the facade layer (between controllers and the services) and as with the case above, the facade shouldn't have to worry about this either.
Does anyone have any ideas? I am perfectly willing to bypass JPA and use native Hibernate concepts.
Thank you,
Ted