Why is “public” not allowed for properties in JPA entities?

有些话、适合烂在心里 提交于 2019-12-19 18:24:49

问题


The JPA 2.0 specification says on page 22:

The instance variables of a class must be private, protected, or package visibility independent of whether field access or property access is used. When property access is used, the property accessor methods must be public or protected.

Why isn't public access allowed?


回答1:


With public fields, there would be no way for proxying to work reliably -- if someone accesses a field directly, then there is no simple way for the persistence framework to intercept that call and (say) initialize the containing object, if it's a proxy.

If field access is not possible, synthetic getter methods can be generated on the proxy object to intercept the method calls and do any required 'behind-the-scenes' work.




回答2:


With DataNucleus as JPA provider you could use public fields, but you would then need to mark any classes that access these fields as "persistence aware" (see the DataNucleus docs), so they can be enhanced to cater for this




回答3:


To be sure that accessor methods are used (like get... set.... is.... ). Thats part of the isolation principle.



来源:https://stackoverflow.com/questions/2040836/why-is-public-not-allowed-for-properties-in-jpa-entities

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