简体   繁体   中英

Java JPA implementation - how are properties read/set?

I am reading the Beginning Java EE6 Platform and Glassfish 3 book and I have some minor difficulties at understanding Access type on field/properties. What is the difference between the two of them?

Is it how the properties are read/set by the JPA implementation (in this case EclipseLink)? Like, if it is property access the values are read/set through possible validations etc that can be placed in the get/set method, while the field access option does not do setting/getting values through these methods but straight on the fields? And does the type get set by where I am placing the @Id annotation?

The @Access annotation type indicates how the JPA should set or get the field in your object. An AccessType.FIELD the JPA will set the field directly with reflection and will not use any provided setter method., very useful if your class tracks the "dirtyness" of a field through the setter methods. In contrast setting @Access(value=AccessType.PROPERTY) will instruct the JPA to use the setter and getter methods when it accesses fields.

You can prove this to yourself by adding logging or System.out.println s to your setter methods and then making changes to the @Access annotation. For example:

@Id
@Access(value=AccessType.PROPERTY)
private Long Id;
public void setId(Long id) { System.out.println("SET"); this.Id = id; }

Will print SET and this:

@Id
@Access(value=AccessType.FIELD)
private Long Id;
public void setId(Long id) { System.out.println("SET"); this.Id = id; }

Will NOT!

It also does not matter where you place the annotations, at least in Hibernate ;-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM