An entity is a lightweight persistence domain object. Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table. The primary programming artifact of an entity is the entity class, although entities can use helper classes. The persistent state of an entity is represented through either persistent fields or persistent properties. These fields or properties
use object/relational mapping annotations to map the entities and entity relationships to the relational data in the underlying data store. An entity class must follow these requirements. The class must be annotated with the The class must have a public or protected, no-argument
constructor. The class may have other constructors. The class must not be declared If an entity instance is passed by value as a detached object, such as through a session bean's remote business interface, the class must implement the Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. Persistent instance variables must be declared private, protected, or package-private and can be accessed directly only by the entity class's methods. Clients must access the entity's state through accessor or business methods. 37.1.2 Persistent Fields and Properties in Entity ClassesThe persistent state of an entity can be accessed through either the entity's instance variables or properties. The fields or properties must be of the following Java language types:
Entities may use persistent fields, persistent properties, or a combination of both. If the mapping annotations are applied to the entity's instance variables, the entity uses persistent fields. If the mapping annotations are applied to the entity's getter methods for JavaBeans-style properties, the entity uses persistent properties. 37.1.2.1 Persistent FieldsIf the entity class uses persistent fields, the Persistence runtime accesses entity-class instance variables directly. All fields not annotated 37.1.2.2 Persistent PropertiesIf the entity uses persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter methods that are typically named after the entity class's instance variable names. For every persistent property property of type Type of the entity, there is a getter method
The method signatures for single-valued persistent properties are as follows: Type getProperty() void setProperty(Type type) The object/relational mapping annotations for persistent properties must be applied to the getter methods. Mapping annotations cannot be applied to fields or properties annotated 37.1.2.3 Using Collections in Entity Fields and PropertiesCollection-valued persistent fields and properties must use the supported Java collection interfaces regardless of whether the entity uses persistent fields or properties. The following collection interfaces may be used:
If the entity class uses persistent fields, the type in the preceding method signatures must be one of these collection types. Generic variants of these collection types may also be used. For
example, if it has a persistent property that contains a set of phone numbers, the Set<PhoneNumber> getPhoneNumbers() { ... } void setPhoneNumbers(Set<PhoneNumber>) { ... } If a field or property of an entity consists of a collection of basic types or embeddable classes, use the The two attributes of The following entity, @Entity public class Person { ... @ElementCollection(fetch=EAGER) protected Set<String> nickname = new HashSet(); ... } Collections of entity elements and relationships may be represented by When using
If the key type of a If the key type of a If Java programming language generic types are not used in the relationship field or property, the key class must be explicitly set using the If the If the If the If the entity is part of a one-to-many/many-to-one bidirectional relationship, it will be mapped in the table of the entity that represents the value of the 37.1.2.4 Validating Persistent Fields and PropertiesThe Java API for JavaBeans Validation (Bean Validation) provides a mechanism for validating application data. Bean Validation is integrated into the Java EE containers, allowing the same validation logic to be used in any of the tiers of an enterprise application. Bean Validation constraints may be applied to
persistent entity classes, embeddable classes, and mapped superclasses. By default, the Persistence provider will automatically perform validation on entities with persistent fields or properties annotated with Bean Validation constraints immediately after the Bean Validation constraints are annotations applied to the fields or properties of Java programming language classes. Bean Validation provides a set of constraints as well as an API for defining custom constraints. Custom constraints can be specific combinations of the default constraints, or new constraints that don't use the default constraints. Each constraint is associated with at least one validator class that validates the value of the constrained field or property. Custom constraint developers must also provide a validator class for the constraint. Bean Validation constraints are applied to the persistent fields or properties of persistent classes. When adding Bean Validation constraints, use the same access strategy as the persistent class. That is, if the persistent class uses field access, apply the Bean Validation constraint annotations on the class's fields. If the class uses property access, apply the constraints on the getter methods. Table 21-1 lists Bean Validation's built-in constraints, defined in the All the
built-in constraints listed in Table 21-1 have a corresponding annotation, ConstraintName @Pattern.List({ @Pattern(regexp="..."), @Pattern(regexp="...") }) The following entity class, @Entity public class Contact implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NotNull protected String firstName; @NotNull protected String lastName; @Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\." + "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9]" + "(?:[a-z0-9-]*[a-z0-9])?", message = "{invalid.email}") protected String email; @Pattern(regexp = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message = "{invalid.phonenumber}") protected String mobilePhone; @Pattern(regexp = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message = "{invalid.phonenumber}") protected String homePhone; @Temporal(javax.persistence.TemporalType.DATE) @Past protected Date birthday; ... } The
The The The 37.1.3 Primary Keys in EntitiesEach entity has a unique object identifier. A customer entity, for example, might be identified by a customer number. The unique identifier, or primary key, enables clients to locate a particular entity instance. Every entity must have a primary key. An entity may have either a simple or a composite primary key. Simple primary keys use the Composite primary keys are used when a primary key consists of more than one attribute, which corresponds to a set of single persistent properties or fields. Composite primary keys must be defined in a primary
key class. Composite primary keys are denoted using the The primary key, or the property or field of a composite primary key, must be one of the following Java language types:
Floating-point types should never be used in primary keys. If you use a generated primary key, only integral types will be portable. A primary key class must meet these requirements.
The following primary key class is a composite key, and the public final class LineItemKey implements Serializable { private Integer customerOrder; private int itemId; public LineItemKey() {} public LineItemKey(Integer order, int itemId) { this.setCustomerOrder(order); this.setItemId(itemId); } @Override public int hashCode() { return ((this.getCustomerOrder() == null ? 0 : this.getCustomerOrder().hashCode()) ^ ((int) this.getItemId())); } @Override public boolean equals(Object otherOb) { if (this == otherOb) { return true; } if (!(otherOb instanceof LineItemKey)) { return false; } LineItemKey other = (LineItemKey) otherOb; return ((this.getCustomerOrder() == null ? other.getCustomerOrder() == null : this.getCustomerOrder() .equals(other.getCustomerOrder())) && (this.getItemId() == other.getItemId())); } @Override public String toString() { return "" + getCustomerOrder() + "-" + getItemId(); } /* Getters and setters */ } 37.1.4 Multiplicity in Entity RelationshipsMultiplicities are of the following types.
37.1.5 Direction in Entity RelationshipsThe direction of a relationship can be either bidirectional or unidirectional. A bidirectional relationship has both an owning side and an inverse side. A unidirectional relationship has only an owning side. The owning side of a relationship determines how the Persistence runtime makes updates to the relationship in the database. 37.1.5.1 Bidirectional RelationshipsIn a bidirectional relationship, each entity has a relationship field or property that refers to the other entity. Through the relationship field or property, an entity class's code can access its related object. If an entity has a related field, the entity is said to "know" about its related object. For example, if Bidirectional relationships must follow these rules.
37.1.5.2 Unidirectional RelationshipsIn a unidirectional relationship, only one entity has a relationship field or property that refers to the other. For example,
37.1.5.3 Queries and Relationship DirectionJava Persistence query language and Criteria API queries often navigate across relationships. The direction of a relationship determines whether a query can navigate from one entity to another. For example, a query can navigate from 37.1.5.4 Cascade Operations and RelationshipsEntities that use relationships often have dependencies on the existence of the other entity in the relationship. For example, a line item is part of an order; if the order is deleted, the line item also should be deleted. This is called a cascade delete relationship. The
Table 37-1 Cascade Operations for Entities
Cascade delete relationships are specified using the @OneToMany(cascade=REMOVE, mappedBy="customer") public Set<CustomerOrder> getOrders() { return orders; } 37.1.5.5 Orphan Removal in RelationshipsWhen a target entity in a one-to-one or one-to-many relationship is removed from the
relationship, it is often desirable to cascade the remove operation to the target entity. Such target entities are considered "orphans," and the The The following example will cascade the remove operation to the orphaned @OneToMany(mappedBy="customer", orphanRemoval="true") public List<CustomerOrder> getOrders() { ... } 37.1.6 Embeddable Classes in EntitiesEmbeddable classes are used to represent the state of an entity but don't have a persistent identity of their own, unlike entity classes. Instances of an embeddable class share the identity of the entity that owns it. Embeddable classes exist only as the state of another entity. An entity may have single-valued or collection-valued embeddable class attributes. Embeddable classes have the same rules as entity classes but are annotated with the The following embeddable class, @Embeddable public class ZipCode { String zip; String plusFour; ... } This embeddable class is used by the @Entity public class Address { @Id protected long id String street1; String street2; String city; String province; @Embedded ZipCode zipCode; String country; ... } Entities that own embeddable classes as part of their persistent state may annotate the field or property with the Embeddable classes may themselves use other embeddable classes to represent their state. They may also contain collections of basic Java programming language types or other embeddable classes. Embeddable classes may also contain relationships to other entities or collections of entities. If the embeddable class has such a relationship, the relationship is from the target entity or collection of entities to the entity that owns the embeddable class. Table of ContentsJava Platform, Enterprise Edition: The Java EE TutorialExpand | Collapse Which of the following is a reason some developers believe a data model is the most important part of the information systems requirement?Some systems developers believe that a data model is the most important part of the statement of information system requirements because: A. the characteristics of data captured during data modeling are crucial in the design of databases, programs, computer screens, and printed reports.
What is the term that refers to the number of instance of entity from a relation that can be associated with the relation?Cardinality of Relationships
Refers to the number of instances of entity A that can be associated with each instance of entity B. One-to-one: Each entity in the relationship will have exactly one related entity.
Is the number of instances of entity B that can or must be associated with each instance of entity A?Cardinality = the number of instances of entity B that can (or must) be associated with each instance of entity A. Cardinality is the maximum number (0, 1 or Many) of records in one file that are linked to a single record in another file and vice versa.
Is an attribute that must have a value for every entity instance?The primary key is an attribute or a set of attributes that uniquely identify a specific instance of an entity. Every entity in the data model must have a primary key whose values uniquely identify instances of the entity.
|