Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should JPA Entities match database constraints and triggers?

Should JPA Entities match the constraints of the database they're mapping? What about database triggers used for data generation, should those be match as well?

like image 253
user623941 Avatar asked Dec 03 '25 11:12

user623941


1 Answers

Yes, you should model the constraints in your JPA model, as it is best to state those constraint explicit in your entities.

On one side because just of documentation purposes (many developers will look into your entity model while nearly none of them will look into the database model when using your beans).

On the other because you can catch wrong input as early as possible (potentially even in your UI), because many frameworks like JSF will look at them.

In addition many of your constraints like @NotNull or @Size will be mapped to database constraints, if you let Hibernate create your database schema.

And you should try to move triggers from your database to your entities - to keep the application logic in one place and make such things explicit. But it makes no sense to double that logic - so if you need to keep these triggers in the database, don't add the same in the entities (but you should mention the triggers in the JavaDoc then).

like image 103
Tobias Liefke Avatar answered Dec 05 '25 00:12

Tobias Liefke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!