Java Reference
In-Depth Information
Listing 6-4. A Class with Field Access
import javax.persistence.*;
@Entity
public class Sample {
@Id
int id;
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
If instead the annotation is applied to the getter for the field, as shown in Listing 6-5, then
property access will be used.
Listing 6-5. The Same Class with Property Access
import javax.persistence.*;
@Entity
public class Sample {
int id;
@Id
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
Here you can see one of the strengths of the annotations approach—because the annota-
tions are placed inline with the source code, information can be extracted from the context of
the mapping in the code, allowing many mapping decisions to be inferred rather than stated
explicitly—which helps to further reduce the verbosity of the annotations.
By default, the @Id annotation will automatically determine the most appropriate primary
key generation strategy to use—you can override this by also applying the @GeneratedValue
annotation. This takes a pair of attributes: strategy and generator . The strategy attribute must
be a value from the javax.persistence.GeneratorType enumeration. If you do not specify a
generator type, the default is AUTO . There are four different types of primary key generators on
GeneratorType , as follows:
Search WWH ::




Custom Search