Java Reference
In-Depth Information
Looking again at listing 9.3 , you may be asking yourself why the @Column annotation
was placed directly on the User object's properties. Does the annotation have to go there?
Can the annotation be placed on the getter or setter methods instead? We'll explore this
next when we discuss the difference between field- and property-based persistence.
Field- versus property-based persistence
With JPA, you have a choice of where you place @Column annotations. Your first choice
is to place the annotations on the variables of the class. This is known as field-based access.
Here's an example:
@Column(name="USER_ID")
private Long id;
When you use field-based access, JPA will get and set the value directly by accessing the
private variable. This may be acceptable if your domain model object is a simple bean with
getters and setters that have no business logic. The other choice you have for the placement
of your annotations is on the getter methods of the class (annotations on setter methods are
ignored). This is known as property-based access. Here's an example:
@Column(name="USER_ID")
public Long getId() { return id; }
public Long setId(Long id) {
this.id = (id <= 0) ? 0 : id;
}
In this example, notice that the annotation is on the getter method and that the setter method
has some simple business logic. When you use property-based access, JPA will get the
value by using the getter method and set the value by using the setter method. If you do
have some business logic in your getter or setter methods, you should use property-based
access so that JPA uses the getter and setter methods instead of accessing the private vari-
able directly.
With JPA 1.0, you were limited to using either field-based access or property-based access
and you couldn't mix and match the two within an object hierarchy. For example, Ac-
tionBazaar has a User superclass with Seller and Bidder child classes. With JPA
1.0, all three objects ( User , Seller , Bidder ) had to use either field-based access or
property-based access. This has changed in JPA 2.0 with the introduction of the @Access
annotation.
Search WWH ::




Custom Search