Best way to validate rows before save?

Hi guys,

Looking for a place where we can put pre-save data-consistency logic (which sometime needs to do DB lookup). Trying to put it below service layer because there is a chance that update will be initiated from another service and people can forget to call validation logic.

EventListener with hooks looks promising (all rows go through it), but when trying to query DB from a hook I get into infinite loop. Was able to fix using @Transaction annotation, but not sure it’s the best way to do it. Also when throw an error from @PrePersist hook it gets wrapper to Flush/Transaction error.

I can keep bending EvenListener and get it working, but now not sure it’s intended for this kind of usage. Looking for some best-practices. What is the best way to consistently apply data quality checks before create/update/delete?

Thanks

Dont know a hibernate solution, but in code i would make my entity package private and allow it to be accesible only through one service. Additionaly you could provide other a public DTO to interact with your entity and make the checks on the conversion from DTO to entity in your service.

1 Like