I'm a JPA beginner and i'm actually trying to learn the开发者_开发技巧 basics of this API, my questionn is ; is there a difference between applying an annotation to a field and applying it to its getter?
I don't have a good JPA reference for it, but if you're using Hibernate there are some notes about this choice in the Hibernate Annotations reference. It says:
Depending on whether you annotate fields or methods, the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing annotations in both fields and methods should be avoided. Hibernate will guess the access type from the position of @Id or @EmbeddedId.
Hibernate uses reflection to access the values, and this choice will determine whether it calls the getters and setters or uses direct field access.
Which choice is actually better is debatable and may vary depending on whether you do work beyond the obvious getting and setting of fields in your getters and setters.
There is a difference between Field and Property access as others have stated. Field indicates direct access by the persistence provider and Property (method access) indicates the use of the getter/setter of your choosing to access the data.
I would recommend starting with Field access as in my experience this is easier/safer for new users to get started with. Property access can be very useful, and may be generally preferred by some, but it can also lead to problems if you are not careful (due to the additional behavior that getters and setters may have). So in general it is best to use Field access as a beginner unless you have a reason to use Property access.
I also recommend picking up a copy of Pro JPA 2 by Mike Keith and Merrick Schincariol if you are just getting started with JPA. It covers this and many other related topics.
精彩评论