Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

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

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

Entities

Requirements for Entity Classes

Persistent Fields and Properties in Entity Classes

Persistent Fields

Persistent Properties

Primary Keys in Entities

Primary Key Classes

Multiplicity in Entity Relationships

Direction in Entity Relationships

Bidirectional Relationships

Unidirectional Relationships

Queries and Relationship Direction

Cascade Deletes and Relationships

Entity Inheritance

Abstract Entities

Mapped Superclasses

Non-Entity Superclasses

Entity Inheritance Mapping Strategies

Managing Entities

The Persistence Context

TheEntityManager Interface

Container-Managed Entity Managers

Application-Managed Entity Managers

Finding Entities Using theEntityManager

Managing an Entity Instance's Life Cycle

Creating Queries

Persistence Units

Thepersistence.xml File

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Entities

An 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 Classes

An entity class must follow these requirements:

  • The class must be annotated with thejavax.persistence.Entity annotation.

  • The class must have a public or protected, no-argument constructor. The class may have other constructors.

  • The class must not be declaredfinal. No methods or persistent instance variables must be declaredfinal.

  • If an entity instance be passed by value as a detached object, such as through a session bean’s remote business interface, the class must implement theSerializable interface.

  • 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 only be accessed directly by the entity class’s methods. Clients must access the entity’s state through accessor or business methods.

Persistent Fields and Properties in Entity Classes

The 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:

  • Java primitive types

  • java.lang.String

  • Other serializable types including:

    • Wrappers of Java primitive types

    • java.math.BigInteger

    • java.math.BigDecimal

    • java.util.Date

    • java.util.Calendar

    • java.sql.Date

    • java.sql.Time

    • java.sql.TimeStamp

    • User-defined serializable types

    • byte[]

    • Byte[]

    • char[]

    • Character[]

  • Enumerated types

  • Other entities and/or collections of entities

  • Embeddable classes

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 Fields

If 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 Properties

If 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:

  • java.util.Collection

  • java.util.Set

  • java.util.List

  • java.util.Map

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 Entities

Each 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:

  • Java primitive types

  • Java primitive wrapper types

  • java.lang.String

  • java.util.Date (the temporal type should beDATE)

  • java.sql.Date

Floating point types should never be used in primary keys. If youuse a generated primary key, only integral types will be portable.

Primary Key Classes

A primary key class must meet these requirements:

  • The access control modifier of the class must bepublic.

  • The properties of the primary key class must bepublic orprotected if property-based access is used.

  • The class must have a public default constructor.

  • The class must implement thehashCode() andequals(Object other) methods.

  • The class must be serializable.

  • A composite primary key must be represented and mapped to multiple fields or properties of the entity class, or must be represented and mapped as an embeddable class.

  • If the class is mapped to multiple fields or properties of the entity class, the names and types of the primary key fields or properties in the primary key class must match those of the entity class.

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 Relationships

There 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 Relationships

The 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 Relationships

In 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:

  • The inverse side of a bidirectional relationship must refer to its owning side by using themappedBy element of the@OneToOne,@OneToMany, or@ManyToMany annotation. ThemappedBy element designates the property or field in the entity that is the owner of the relationship.

  • The many side of many-to-one bidirectional relationships must not define themappedBy element. The many side is always the owning side of the relationship.

  • For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

  • For many-to-many bidirectional relationships either side may be the owning side.

Unidirectional Relationships

In 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 Direction

Java 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 Relationships

Entities 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 Inheritance

Entities 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 Entities

An 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 Superclasses

Entities 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 Superclasses

Entities 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 Strategies

You 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:

  • A single table per class hierarchy

  • A table per concrete entity class

  • A “join” strategy, where fields or properties that are specific to a subclass are mapped to a different table than the fields or properties that are common to the parent class

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 Strategy

With 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

Type

Name

Description

String

name

The name of the column inthe table to be used as the discriminator column. The default isDTYPE.This element is optional.

DiscriminatorType

discriminatorType

The type of the column to be used asa discriminator column. The default isDiscriminatorType.STRING. This element is optional.

String

columnDefinition

The SQL fragmentto use when creating the discriminator column. The default is generated by thePersistence provider, and is implementation-specific. This element is optional.

String

length

The column length forString-baseddiscriminator types. This element is ignored for non-String discriminator types. The default is 31.This element is optional.

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 Strategy

In 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 Strategy

In 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.

PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp