Java Reference
In-Depth Information
terms of fields, Hibernate accesses the fields directly when loading and saving
objects. Alternatively, if the mapping is defined using properties, Hibernate calls get-
ters and setters. Table 6.1 lists the pros and cons of each option.
Table 6.1
Pros and cons of mapping fields and properties
Pros
Cons
Properties
Encapsulation
Accessors can transform values
It's the default
Must define accessors (but they
bb can be private)
Fields
No need to define accessors—
bb especially setters
Less encapsulation
Not the default, so that mapping
bb becomes more verbose
Hibernate's O/R mapping uses the <property> element to map either a field or a
property to a column, which can be confusing at first. For example, you can map
the price property of a MenuItem using this:
class MenuMenu {
public double getPrice() {…};
private void setPrice(double newPrice) {…};
}
<class name="MenuItem" …>
<property name="price" column="PRICE"/>
</class>
Hibernate calls accessors when it loads and saves a MenuItem . It calls the get-
Price() getter when it saves a MenuItem and will call the setPrice() setter when it
loads a MenuItem . Note that accessors can be private if necessary.
Alternatively, you can map the price field using this:
class MenuMenu {
private double price;
}
<class name="MenuItem" …>
<property name=" price" column="PRICE" access="field"/>
</class>
 
Search WWH ::




Custom Search