2. Using the Tutorial Examples 3. Getting Started with Web Applications 5. JavaServer Pages Technology 7. JavaServer Pages Standard Tag Library 10. JavaServer Faces Technology 11. Using JavaServer Faces Technology in JSP Pages 12. Developing with JavaServer Faces Technology 13. Creating Custom UI Components 14. Configuring JavaServer Faces Applications 15. Internationalizing and Localizing Web Applications 16. Building Web Services with JAX-WS 17. Binding between XML Schema and Java Classes 19. SOAP with Attachments API for Java 21. Getting Started with Enterprise Beans 23. A Message-Driven Bean Example 24. Introduction to the Java Persistence API Requirements for Entity Classes Persistent Fields and Properties in Entity Classes Multiplicity in Entity Relationships Direction in Entity Relationships Queries and Relationship Direction Container-Managed Entity Managers Application-Managed Entity Managers Finding Entities Using theEntityManager Managing an Entity Instance's Life Cycle 25. Persistence in the Web Tier 26. Persistence in the EJB Tier 27. The Java Persistence Query Language 28. Introduction to Security in the Java EE Platform 29. Securing Java EE Applications 31. The Java Message Service API 32. Java EE Examples Using the JMS API 36. The Coffee Break Application | EntitiesAn entity is a lightweight persistence domain object. Typically an entity represents atable in a relational database, and each entity instance corresponds to a rowin that table. The primary programming artifact of an entity is the entityclass, although entities can use helper classes. The persistent state of an entity is represented either through persistent fields orpersistent properties. These fields or properties use object/relational mapping annotations to map theentities and entity relationships to the relational data in the underlying data store. Requirements for Entity ClassesAn entity class must follow these requirements:
Persistent Fields and Properties in Entity ClassesThe persistent state of an entity can be accessed either through the entity’sinstance variables or through JavaBeans-style properties. The fields or properties must be ofthe following Java language types:
Entities may either use persistent fields or persistent properties. If the mapping annotationsare applied to the entity’s instance variables, the entity uses persistent fields. Ifthe mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties,the entity uses persistent properties. You cannot apply mapping annotations to both fields andproperties in a single entity. Persistent FieldsIf the entity class uses persistent fields, the Persistence runtime accesses entity classinstance variables directly. All fields not annotatedjavax.persistence.Transient or not marked asJavatransient will be persisted to the data store. The object/relational mapping annotations mustbe applied to the instance variables. Persistent PropertiesIf the entity uses persistent properties, the entity must follow the method conventionsof JavaBeans components. JavaBeans-style properties use getter and setter methods that are typicallynamed after the entity class’s instance variable names. For every persistent propertypropertyof typeType of the entity, there is a getter methodgetProperty andsetter methodsetProperty. If the property is a boolean, you may useisProperty instead ofgetProperty. For example, if aCustomer entity uses persistent properties,and has a private instance variable calledfirstName, the class defines agetFirstName andsetFirstName method for retrieving and setting the state of thefirstName instance variable. The method signature for single-valued persistent properties are as follows: Type getProperty()void setProperty(Type type) Collection-valued persistent fields and properties must use the supported Java collection interfaces regardlessof whether the entity uses persistent fields or properties. The following collection interfacesmay be used:
If the entity class uses persistent fields, the type in the abovemethod signatures must be one of these collection types. Generic variants of these collectiontypes may also be used. For example, if theCustomer entity has apersistent property that contains a set of phone numbers, it would have thefollowing methods: Set<PhoneNumber> getPhoneNumbers() {}void setPhoneNumbers(Set<PhoneNumber>) {}The object/relational mapping annotations for must be applied to the getter methods. Mappingannotations cannot be applied to fields or properties annotated@Transient or markedtransient. Primary Keys in EntitiesEach entity has a unique object identifier. A customer entity, for example, mightbe identified by a customer number. The unique identifier, orprimary key, enablesclients to locate a particular entity instance. Every entity must have a primarykey. An entity may have either a simple or a composite primary key. Simple primary keys use thejavax.persistence.Id annotation to denote the primary key propertyor field. Composite primary keys must correspond to either a single persistent property or field,or to a set of single persistent properties or fields. Composite primary keysmust be defined in a primary key class. Composite primary keys are denotedusing thejavax.persistence.EmbeddedId andjavax.persistence.IdClass annotations. The primary key, or the property or field of a composite primarykey, must be one of the following Java language types:
Floating point types should never be used in primary keys. If youuse a generated primary key, only integral types will be portable. Primary Key ClassesA primary key class must meet these requirements:
The following primary key class is a composite key, theorderId anditemId fields together uniquely identify an entity. public final class LineItemKey implements Serializable { public Integer orderId; public int itemId; public LineItemKey() {} public LineItemKey(Integer orderId, int itemId) { this.orderId = orderId; this.itemId = itemId; } public boolean equals(Object otherOb) { if (this == otherOb) { return true; } if (!(otherOb instanceof LineItemKey)) { return false; } LineItemKey other = (LineItemKey) otherOb; return ( (orderId==null?other.orderId==null:orderId.equals (other.orderId) ) && (itemId == other.itemId) ); } public int hashCode() { return ( (orderId==null?0:orderId.hashCode()) ^ ((int) itemId) ); } public String toString() { return "" + orderId + "-" + itemId; }}Multiplicity in Entity RelationshipsThere are four types of multiplicities: one-to-one, one-to-many, many-to-one, and many-to-many. One-to-one: Each entity instance is related to a single instance of another entity.For example, to model a physical warehouse in which each storage bin containsa single widget,StorageBin andWidget would have a one-to-one relationship. One-to-onerelationships use thejavax.persistence.OneToOne annotation on the corresponding persistent property or field. One-to-many: An entity instance can be related to multiple instances of the otherentities. A sales order, for example, can have multiple line items. In theorder application,Order would have a one-to-many relationship withLineItem. One-to-many relationships use thejavax.persistence.OneToMany annotation on the corresponding persistent property or field. Many-to-one: Multiple instances of an entity can be related to a single instanceof the other entity. This multiplicity is the opposite of a one-to-many relationship.In the example just mentioned, from the perspective ofLineItem the relationship toOrder is many-to-one. Many-to-one relationships use thejavax.persistence.ManyToOne annotation on the correspondingpersistent property or field. Many-to-many: The entity instances can be related to multiple instances of each other.For example, in college each course has many students, and every student maytake several courses. Therefore, in an enrollment application,Course andStudent would havea many-to-many relationship. Many-to-many relationships use thejavax.persistence.ManyToMany annotation on the corresponding persistent propertyor field. Direction in Entity RelationshipsThe direction of a relationship can be either bidirectional or unidirectional. A bidirectionalrelationship has both an owning side and an inverse side. A unidirectional relationshiphas only an owning side. The owning side of a relationship determines howthe Persistence runtime makes updates to the relationship in the database. Bidirectional RelationshipsIn a bidirectional relationship, each entity has a relationship field or property thatrefers to the other entity. Through the relationship field or property, an entityclass’s code can access its related object. If an entity has a relatedfield, then the entity is said to “know” about its related object. Forexample, ifOrder knows whatLineItem instances it has and ifLineItem knowswhatOrder it belongs to, then they have a bidirectional relationship. Bidirectional relationships must follow these rules:
Unidirectional RelationshipsIn aunidirectional relationship, only one entity has a relationship field or propertythat refers to the other. For example,LineItem would have a relationshipfield that identifiesProduct, butProduct would not have a relationship field orproperty forLineItem. In other words,LineItem knows aboutProduct, butProductdoesn’t know whichLineItem instances refer to it. Queries and Relationship DirectionJava Persistence query language queries often navigate across relationships. The direction of arelationship determines whether a query can navigate from one entity to another. Forexample, a query can navigate fromLineItem toProduct but cannot navigate in theopposite direction. ForOrder andLineItem, a query could navigate in bothdirections, because these two entities have a bidirectional relationship. Cascade Deletes and RelationshipsEntities that use relationships often have dependencies on the existence of the otherentity in the relationship. For example, a line item is part of anorder, and if the order is deleted, then the line item shouldalso be deleted. This is called a cascade delete relationship. Cascade delete relationships are specified using thecascade=REMOVE element specification for@OneToOneand@OneToMany relationships. For example: @OneToMany(cascade=REMOVE, mappedBy="customer")public Set<Order> getOrders() { return orders; }Entity InheritanceEntities support class inheritance, polymorphic associations, and polymorphic queries. They can extend non-entityclasses, and non-entity classes can extend entity classes. Entity classes can be bothabstract and concrete. Theroster example application demonstrates entity inheritance, and is described inEntity Inheritance in theroster Application. Abstract EntitiesAn abstract class may be declared an entity by decorating the class with@Entity. Abstract entities differ from concrete entities only in that they cannot beinstantiated. Abstract entities can be queried just like concrete queries. If an abstract entityis the target of a query, the query operates on all theconcrete subclasses of the abstract entity. @Entitypublic abstract class Employee { @Id protected Integer employeeId; ...}@Entitypublic class FullTimeEmployee extends Employee { protected Integer salary; ...}@Entitypublic class PartTimeEmployee extends Employee { protected Float hourlyWage;}Mapped SuperclassesEntities may inherit from superclasses that contain persistent state and mapping information, butare not entities. That is, the superclass is not decorated with the@Entityannotation, and is not mapped as an entity by the Java Persistence provider.These superclasses are most often used when you have state and mapping informationcommon to multiple entity classes. Mapped superclasses are specified by decorating the class with thejavax.persistence.MappedSuperclass annotation. @MappedSuperclasspublic class Employee { @Id protected Integer employeeId; ...}@Entitypublic class FullTimeEmployee extends Employee { protected Integer salary; ...}@Entitypublic class PartTimeEmployee extends Employee { protected Float hourlyWage; ...}Mapped superclasses are not queryable, and can’t be used inEntityManager orQuery operations. You must use entity subclasses of the mapped superclass inEntityManagerorQuery operations. Mapped superclasses can’t be targets of entity relationships. Mapped superclassescan be abstract or concrete. Mapped superclasses do not have any corresponding tables in the underlying datastore. Entitiesthat inherit from the mapped superclass define the table mappings. For instance, inthe code sample above the underlying tables would beFULLTIMEEMPLOYEE andPARTTIMEEMPLOYEE, but thereis noEMPLOYEE table. Non-Entity SuperclassesEntities may have non-entity superclasses, and these superclasses can be either abstract orconcrete. The state of non-entity superclasses is non-persistent, and any state inherited fromthe non-entity superclass by an entity class is non-persistent. Non-entity superclasses may notbe used inEntityManager orQuery operations. Any mapping or relationship annotations innon-entity superclasses are ignored. Entity Inheritance Mapping StrategiesYou can configure how the Java Persistence provider maps inherited entities to theunderlying datastore by decorating the root class of the hierarchy with thejavax.persistence.Inheritanceannotation. There are three mapping strategies that are used to map the entitydata to the underlying database:
The strategy is configured by setting thestrategy element of@Inheritance to oneof the options defined in thejavax.persistence.InheritanceType enumerated type: public enum InheritanceType { SINGLE_TABLE, JOINED, TABLE_PER_CLASS};The default strategy isInheritanceType.SINGLE_TABLE, and is used if the@Inheritance annotation isnot specified on the root class of the entity hierarchy. The Single Table per Class Hierarchy StrategyWith this strategy, which corresponds to the defaultInheritanceType.SINGLE_TABLE, all classes inthe hierarchy are mapped to a single table in the database. This tablehas adiscriminator column, a column that contains a value that identifies the subclassto which the instance represented by the row belongs. The discriminator column can be specified by using thejavax.persistence.DiscriminatorColumn annotation onthe root of the entity class hierarchy. Table 24-1@DiscriminatorColumn Elements
Thejavax.persistence.DiscriminatorType enumerated type is used to set the type of the discriminatorcolumn in the database by setting thediscriminatorType element of@DiscriminatorColumn to oneof the defined types.DiscriminatorType is defined as: public enum DiscriminatorType { STRING, CHAR, INTEGER};If@DiscriminatorColumn is not specified on the root of the entity hierarchy anda discriminator column is required, the Persistence provider assumes a default column nameofDTYPE, and column type ofDiscriminatorType.STRING. Thejavax.persistence.DiscriminatorValue annotation may be used to set the value entered into thediscriminator column for each entity in a class hierarchy. You may only decorateconcrete entity classes with@DiscriminatorValue. If@DiscriminatorValue is not specified on an entity in a class hierarchy thatuses a discriminator column, the Persistence provider will provide a default, implementation-specific value.If thediscriminatorType element of@DiscriminatorColumn isDiscriminatorType.STRING, the default value isthe name of the entity. This strategy provides good support for polymorphic relationships between entities and queries thatcover the entire entity class hierarchy. However, it requires the columns that containthe state of subclasses to be nullable. The Table per Concrete Class StrategyIn this strategy, which corresponds toInheritanceType.TABLE_PER_CLASS, each concrete class is mappedto a separate table in the database. All fields or properties in theclass, including inherited fields or properties, are mapped to columns in the class’stable in the database. This strategy provides poor support for polymorphic relationships, and usually requires either SQLUNION queries or separate SQL queries for each subclass for queries that coverthe entire entity class hierarchy. Support for this strategy is optional, and may not be supported byall Java Persistence API providers. The default Java Persistence API provider in the ApplicationServer does not support this strategy. The Joined Subclass StrategyIn this strategy, which corresponds toInheritanceType.JOINED, the root of the class hierarchyis represented by a single table, and each subclass has a separate tablethat only contains those fields specific to that subclass. That is, the subclasstable does not contain columns for inherited fields or properties. The subclass tablealso has a column or columns that represent its primary key, which isa foreign key to the primary key of the superclass table. This strategy provides good support for polymorphic relationships, but requires one or morejoin operations to be performed when instantiating entity subclasses. This may result inpoor performance for extensive class hierarchies. Similarly, queries that cover the entire classhierarchy require join operations between the subclass tables, resulting in decreased performance. Some Java Persistence API providers, including the default provider in the Application Server,require a discriminator column in the table that corresponds to the root entitywhen using the joined subclass strategy. If you are not using automatic tablecreation in your application, make sure the database table is set up correctlyfor the discriminator column defaults, or use the@DiscriminatorColumn annotation to matchyour database schema. For information on discriminator columns, seeThe Single Table per Class Hierarchy Strategy. Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices |