2020-03-31

Hibernate JPA @Access Example

The @Access annotation is used to specify the access type of the associated entity class, mapped superclass, or embeddable class, or entity attribute.

As a JPA provider, Hibernate can introspect both the entity attributes (instance fields) or the accessors (instance properties). By default, the placement of the @Id annotation gives the default access strategy. When placed on a field, Hibernate will assume field-based access. When placed on the identifier getter, Hibernate will use property-based access.

Field-based access

@Entity(name = "Book")
public static class Book {

@Id
private Long id;

private String title;

private String author;

//Getters and setters are omitted for brevity
}

When using field-based access, adding other entity-level methods is much more flexible because Hibernate won’t consider those part of the persistence state. To exclude a field from being part of the entity persistent state, the field must be marked with the @Transient annotation.

Another advantage of using field-based access is that some entity attributes can be hidden from outside the entity.

An example of such attribute is the entity @Version field, which, usually, does not need to be manipulated by the data access layer.

With field-based access, we can simply omit the getter and the setter for this version field, and Hibernate can still leverage the optimistic concurrency control mechanism.

Property-based access

@Entity(name = "Book")
public static class Book {

private Long id;

private String title;

private String author;

@Id
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}
}

When using property-based access, Hibernate uses the accessors for both reading and writing the entity state. Every other method that will be added to the entity (e.g. helper methods for synchronizing both ends of a bidirectional one-to-many association) will have to be marked with the @Transient annotation.


No comments:

Post a Comment