2.4. Entity
JPA recognizes two types of persistent classes: entity classes and embeddable classes.
Each persistent instance of an entity class - each entity - represents a unique datastore record.
You can use the EntityManager to find an entity by its persistent identity (covered later in this chapter), or use a Query to find entities matching certain criteria.
An instance of an embeddable class, on the other hand, is only stored as part of a separate entity.
Embeddable instances have no persistent identity, and are never returned directly from the EntityManager or from a Query unless the query uses a projection on owning class to the embedded instance.
For example, if Address is embedded in Company, then a query "SELECT a FROM Address a" will never return the embedded Address of Company; but a projection query such as "SELECT c.address FROM Company c" will.
Despite these differences, there are few distinctions between entity classes and embeddable classes. In fact, writing either type of persistent class is a lot like writing any other class. There are no special parent classes to extend from, field types to use, or methods to write. This is one important way in which JPA makes persistence transparent to you, the developer.
|
|
JPA supports both fields and JavaBean properties as persistent state. For simplicity, however, we will refer to all persistent state as persistent fields, unless we want to note a unique aspect of persistent properties. |
package org.mag;
/**
* Example persistent class. Notice that it looks exactly like any other
* class. JPA makes writing persistent classes completely transparent.
*/
public class Magazine {
private String isbn;
private String title;
private Set articles = new HashSet();
private Article coverArticle;
private int copiesSold;
private double price;
private Company publisher;
private int version;
protected Magazine() {
}
public Magazine(String title, String isbn) {
this.title = title;
this.isbn = isbn;
}
public void publish(Company publisher, double price) {
this.publisher = publisher;
publisher.addMagazine(this);
this.price = price;
}
public void sell() {
copiesSold++;
publisher.addRevenue(price);
}
public void addArticle(Article article) {
articles.add(article);
}
// rest of methods omitted
}