Is a method in a JPA entity allowed to throw an Exception?

耗尽温柔 提交于 2019-12-06 13:31:45

A first place to start would be to enhance your Entities at build time, or use the -javaagent! Don't use openjpa.RuntimeUnenhancedClasses as there are lots of known bugs with that feature.

No its not illegal, and some JPA implementations (e.g DataNucleus JPA) don't go about calling getters (except when using property access, which you aren't), those are for the developer to call. It also isn't for persistence specifications to impose anything on a developer; there is no "right" way to use a language and design your classes so if you want to have model classes with behaviour then fine, and they should be persistable in the same way

Even though it can be done, it doesn't mean you should. Throwing exceptions in an entity seems like a bad coding smell to me. Entities should not have any business logic, so exception handling in there would be out of place, anyway.

Java EE design patterns encourage a procedural way of thinking, applying OO concepts at the entity level is OK for modeling data (inheritance, polymorphism, etc.) but not behavior - that is to say, validation logic, business logic etc. should reside outside entities and exist only in business classes. The only business logic that makes sense to put in an entity, would be the named queries that apply to it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!