Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 25

Enterprise Beans

Enterprise beans are the Java EE server side components that run inside the ejb container and encapsulates the business logic of an enterprise application. Enterprise applications are the software applications developed intended to use at large scale. These applications involves large number of data accessing concurrently by many users. Enterprise beans are used to perform various types of task like interacting with the client, maintaining session for the clients retrieving and holding data from the database and communicating with the server. Benefits of enterprise beans: Enterprise beans are widely used for developing large and distributed applications. EJB container provides the system-level services (like transaction management and security authorization) to the enterprise beans. These services simplifies the development process of large and distributed applications and the developer just have to concentrate on solving the problem occurred in it. The client developer can focus only on the representation style of the client as all the business logic of the application is contained in the enterprise beans. The client developer does not bother about the code that implements business logic or the logic to access the databases. This means that the clients are thinner. It benefits the client to be thin because the client runs on the small devices. Developing new applications from the existing beans is much easier because the enterprise beans are portable components. That means applications developed by using the enterprise components can run on any complaint J2EE server. When to use the enterprise beans: Some of the points are illustrated below that signifies the use of enterprise beans.
y

y y

Applications developed by using the enterprise beans deal with a variety of clients, simply by writing few lines of code, so that the client can locate the enterprise beans. The client locating the enterprise bean may be various, numerous and thin. Enterprise beans support transaction to ensure the integrity of the database. Transaction is the mechanism of managing the concurrent access of shared objects. Managing the fast growing number of users requires distributed application components across multiple machines means that the application must be scalable.

Types of enterprise beans: EJB 3.0 defines two types of enterprise beans. These are: 1. Session bean: These types of beans directly interact with the client and contains business logic of the business application. 2. Message driven bean: It works like a listener or a consumer for a particular messaging service such as Java Message API or JPA for short.

Session Beans
What is a Session bean A session bean is the enterprise bean that directly interact with the user and contains the business logic of the enterprise application. A session bean represents a single client accessing the enterprise application deployed on the server by invoking its method. An application may contain multiple sessions depending upon the number of users accessing to the application. A session bean makes an interactive session only for a single client and shields that client from complexities just by executing the business task on server side. For example, whenever a client wants to perform any of these actions such as making a reservation or validating a credit card, a session bean should be used. The session bean decides what data is to be modified. Typically, the session bean uses an entity bean to access or modify data. They implement business logic, business rules, algorithms, and work flows. Session beans are relatively short-lived components. The EJB container may destroy a session bean if its client times out. A session bean can neither be shared nor can persist (means its value can not be saved to the database) its value. A session bean can have only one client. As long as the client terminates, session bean associated with this client is also terminated and the data associated with this bean is also destroyed.

The above figure shows how Session Bean interacts with the clients as well as with the Entity Beans.

Session beans are divided into two parts.


y

Stateless Session Beans: A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the instance of bean variables may contain a state specific to that client only for the duration of a method invocation. Once the method is finished, the client-specific state should not be retained i.e. the EJB container destroys a stateless session bean. These types of session beans do not use the class variables (instance variables). So they do not persist data across method invocation and therefore there is no need to passivates the bean's instance. Because stateless session beans can support multiple clients, they provide the better scalability for applications that require large numbers of clients. Stateful Session Beans: These types of beans use the instance variables that allows the data persistent across method invocation because the instance variables allow persistence of data across method invocation. The client sets the data to these variables which he wants to persist. A stateful session bean retains its state across multiple method invocations made by the same client. If the stateful session bean's state is changed during a method invocation, then that state will be available to the same client on the following invocation. The state of a client bean is retained for the duration of the client-bean session. Once the client removes the bean or terminates, the session ends and the state disappears. Because the client interacts with its bean, this state is often called the conversational state. For example, consider a customer using a debit card at an ATM machine. The ATM could perform various operations like checking an account balance, transferring funds, or making a withdrawal. These operations could be performed one by one, by the same customer. So the bean needs to keep track its state for each of these operations to the same client. Thus Stateful session beans has the extra overhead for the server to maintain the state than the stateless session bean.

The user interface calls methods of session beans if the user wants to use the functionality of the session bean. Session beans can call to other session beans and entity beans. When to use session beans: Generally session beans are used in the following circumstances:
y y y

When there is only one client is accessing the beans instance at a given time. When the bean is not persistent that means the bean is going to exist no longer. The bean is implementing the web services.

Stateful session beans are useful in the following circumstances:


y

What the bean wants to holds information about the client across method invocation.

y y

When the bean works as the mediator between the client and the other component of the application. When the bean have to manage the work flow of several other enterprise beans.

Stateless session beans are appropriate in the circumstances illustrated below:


y y

If the bean does not contain the data for a specific client. If there is only one method invocation among all the clients to perform the generic task.

Life Cycle of a Stateless Session Bean: Since the Stateless session bean does not passivates across method calls therefore a stateless session bean includes only two stages. Whether it does not exist or ready for method invocation. A stateless session bean starts its life cycle when the client first obtains the reference of the session bean. For this, the container performs the dependency injection before invoking the annotated @PreConstruct method if any exists. After invoking the annotated @PreConstruct method the bean will be ready to invoke its method by the client.

The above figure demonstrates how the Stateless Session Beans are created and destroyed. The container calls the annotated @PreDestroy method while ending the life cycle of the session bean. After this, the bean is ready for garbage collection. Life Cycle of a Stateful Session Bean: A Stateful session bean starts its life cycle when the client first gets the reference of a stateful session bean. Before invoking the method annotated @PostConstruct the container performs any dependency injection after this the bean is ready. The container may deactivate a bean while in ready state (Generally the container uses the least recently use algorithm to passivates a bean). In the passivate mechanism the bean moves from memory to secondary memory. The container invokes the annotated @PrePassivate method before passivating the bean. If a client invokes a business method on the passivated bean then the container invokes the annotated @PostActivate method to let come the bean in the ready state.

The above image shows the various states of the Stateful Session Beans While ending the life cycle of the bean, the client calls the annotated @Remove method after this the container calls the annotated @PreDestroy method which results in the bean to be ready for the garbage collection.

Message-Driven Bean
What is a Message Driven Bean?
A message driven bean is a stateless, server-side, transaction-aware component that is driven by a Java message (javax.jms.message). It is invoked by the EJB Container when a message is received from a JMS Queue or Topic. It acts as a simple message listener.
A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a JMS message listener, which is similar to an event listener except that it receives messages instead of events. The messages may be sent by any J2EE component--an application client, another enterprise bean, or a Web component--or by a JMS application or system that does not use J2EE technology.

A Java client, an enterprise bean, a Java ServerPagesTM (JSP) component, or a non-J2EE application may send the message. The client sending the message to the destination need not be aware of the MDBs deployed in the EJB Container. However, the message must conform to JMS specifications.

Before MDBs were introduced, JMS described a classical approach to implement asynchronous method invocation. The approach used an external Java program that acted as the listener, and on receiving a message, invoked a session bean method. However, in this approach the message was received outside the application server and was thus not part of a transaction in the EJB Server. MDB solves this problem.

Message processing before (above) and after (below) Message Driven Beans.

Structure of an MDB
y y

It has no home or remote interfaces, and is only a bean class. It resembles a stateless session bean - that is, it has short-lived instances and does not retain state for a client. A client interacts with the MDB in the same way it interacts with a JMS application or JMS server. Through the MDB, the EJB 2.0 Container sets itself up as a listener for asynchronous invocation and directly invokes the bean (no interfaces), which then behaves like an enterprise bean. All instances of a particular MDB type are equivalent as they are not directly visible to the client and maintain no conversational state. This means that the Container can pool instances to enhance scalability.

Lifecycle of an MDB

The EJB Container performs several tasks at the beginning of the life cycle of the MDB:
y

Creates a message consumer (a QueueReceiver or TopicSubscriber) to receive the messages Associates the bean with a destination and connection factory at deployment Registers the message listener and the message acknowledgement mode

y y

The lifecycle of an MDB depends on the lifespan of the EJB Server in which it is deployed. As MDBs are stateless, bean instances are typically pooled by the EJB Server and retrieved by the Container when a message becomes available on the topic or queue.

Writing an MDB
Writing an MDB involves the following tasks:
y

Implement the javax.ejb.MessageDrivenBean and javax.jms.MessageListener interfaces in the MDB class. Provide an implementation of the business logic inside the onMessage(). Provide a setMessageDrivenContext() method that associates the bean with its environment. Provide an ejbCreate() method that returns void and takes no arguments. This method may be blank. Provide an ejbRemove() method implementation. This method may be blank, unless certain resources need to be acquired before the bean goes out of scope.

y y

y y

Entity beans: Entity beans are enterprises beans, which represent persistent data stored in a storage medium, such as relational database an entity bean persists across multiple session and can be accessed by multiple clients. An entity bean acts as an intermediary between a client and a database. For example, consider a bank entity bean that is used for accessing account details from a database. When a client wants to perform a transaction, the information regarding their specific account is loaded into an entity bean instance from the database. Operations are performed on the data present in the instance and updated in the bank?s database at regular intervals. The EJB 3.0 entity beans are used to model and access relational database tables. It is a completely POJO-based persistence framework with annotations that specify how the object should be stored in the database. The EJB 3.0 container does the mapping from the objects to relational database tables automatically and transparently. The Java developer no longer needs to worry about the details of the database table schema, database connection management, and specific database access APIs.

Entity beans do not need to implement home interfaces and business interfaces. They are optional.
An entity bean can be created in two ways: by direct action of the client in which a create() method is called on the bean s home interface, or by some other action that adds data to the database that the bean type represents. In fact, in an environment with legacy data, entity objects may exist before an EJB is even deployed.

ENTITY VS SESSION BEANS


Entity Beans Different from Session Beans?

Entity beans differ from session beans in several ways. Entity beans are persistent, allow shared access, have primary keys, and may participate in relationships with other entity beans.
Persistence

Because the state of an entity bean is saved in a storage mechanism, it is persistent. Persistence means that the entity bean's state exists beyond the lifetime of the application or the J2EE server process. If you've worked with databases, you're familiar with persistent data. The data in a database is persistent because it still exists even after you shut down the database server or the applications it services. There are two types of persistence for entity beans: bean-managed and container-managed. With bean-managed persistence, the entity bean code that you write contains the calls that access the database. If your bean has container-managed persistence, the EJB container automatically generates the necessary database access calls. The code that you write for the entity bean does not include these calls. For additional information, see the section Container-Managed Persistence.
Shared Access

Entity beans may be shared by multiple clients. Because the clients might want to change the same data, it's important that entity beans work within transactions. Typically, the EJB container provides transaction management. In this case, you specify the transaction attributes in the bean's deployment descriptor. You do not have to code the transaction boundaries in the bean--the container marks the boundaries for you. See Chapter 14 for more information.
Primary Key

Each entity bean has a unique object identifier. A customer entity bean, for example, might be identified by a customer number. The unique identifier, or primary key, enables the client to locate a particular entity bean. For more information see the section Primary Keys for BeanManaged Persistence.

Relationships

Like a table in a relational database, an entity bean may be related to other entity beans. For example, in a college enrollment application, StudentEJB and CourseEJB would be related because students enroll in classes. You implement relationships differently for entity beans with bean-managed persistence and those with container-managed persistence. With bean-managed persistence, the code that you write implements the relationships. But with container-managed persistence, the EJB container takes care of the relationships for you. For this reason, relationships in entity beans with container-managed persistence are often referred to as container-managed relationships.

The Life Cycle of an Entity Bean


To understand how to best develop entity beans, it is important to understand how the container manages them. The EJB specification defines just about every major event in an entity bean's life, from the time it is instantiated to the time it is garbage collected. This is called the life cycle, and it provides the bean developer and EJB vendors with all the information they need to develop beans and EJB servers that adhere to a consistent protocol. To understand the life cycle, we will follow an entity instance through several life-cycle events and describe how the container interacts with the entity bean during these events. Figure 6-2 illustrates the life cycle of an entity instance.

Figure 6-2. Entity bean life cycle

We will examine the life cycle of an entity bean and identify the points at which the container would call each of the methods described in the EntityBean interface. Bean instances must implement the EntityBean interface, which means that invocations of the callback methods are invocations on the bean instance itself.
6.3.1. Does Not Exist

The bean instance begins life as a collection of files. Included in that collection are the bean's deployment descriptor, the remote interface, the home interface, the primary key, and all the supporting classes generated at deployment time. At this stage, no instance of the bean exists.
6.3.2. The Pooled State

When the EJB server is started, it reads the bean's files and instantiates several instances of the bean, which it places in a pool. The instances are created by calling the Class.newInstance() method on the bean class. The newInstance() method creates an instance using the default constructor, which has no arguments.[7] This means that the persistent fields of the bean instances are set at their default values; the instances themselves do not represent any data in the database. [7] Constructors should never be defined in the bean class. The default no-argument constructor must be available to the container. Immediately following the creation of an instance, and just before it is placed in the pool, the container assigns the instance its EntityContext. The EntityContext is assigned by calling the setEntityContext() method defined in the EntityBean interface and implemented by the bean class. After the instance has been assigned its context, it is entered into the instance pool. In the instance pool, the bean instance is available to the container as a candidate for serving client requests. Until it is requested, however, the bean instance remains inactive unless it is used to service a find request. Bean instances in the Pooled state typically service find requests, which makes perfectly good sense because they aren't busy and find methods don't rely on the bean instance's state. All instances in the Pooled state are equivalent. None of the instances are assigned to an EJB object, and none of them has meaningful state. At each stage of the entity bean's life cycle the bean container provides varying levels of access. For example, the EJBContext.getPrimary() method will not work if it's invoked during in the ejbCreate() method, but it does work when called in the ejbPostCreate() method. Other EJBContext methods have similar restrictions, as does the JNDI ENC (EJB 1.1). While this section touches on the accessibility of these methods, a complete table that details what is available in each bean class method (ejbCreate(), ejbActivate(), ejbLoad(), etc.) can be found in Appendix B, "State and Sequence Diagrams".

6.3.3. The Ready State

When a bean instance is in the Ready State, it can accept client requests. A bean instance moves to the Ready State when the container assigns it to an EJB object. This occurs under two circumstances: when a new entity bean is being created or when the container is activating an entity.

CMP: Container-Managed Persistence


A CMP bean is an entity bean whose state is synchronized with the database automatically. In other words, the bean developer doesn't need to write any explicit database calls into the bean code; the container will automatically synchronize the persistent fields with the database as dictated by the deployer at deployment time. When a CMP bean is deployed, the deployer uses the EJB tools provided by the vendor to map the persistent fields in the bean to the database. The persistence fields will be a subset of the instance fields, called container-managed fields, as identified by the bean developer in the deployment descriptor. In the case of a relational database, for example, each persistent field will be associated with a column in a table. A bean may map all its fields to one table or, in the case of more sophisticated EJB servers, to several tables. CMP are not limited to relational database. CMP beans can be mapped to object databases, files, and other data stores including legacy systems. With CMP, the bean developer doesn't need to write any database access logic into the bean, but bean is notified by the container when its state is synchronized with the database. The container notifies the bean using the ejbLoad( ) and ejbStore( ) methods. The ejbLoad( ) method alerts the bean that its container-managed fields have just been populated with data from the database. This gives the bean an opportunity to do any post processing before the data can be used by the business methods. The ejbStore( ) method alerts the bean that its data is about to be written to the database. This give the bean an opportunity to do any pre-processing to the fields before they are written to the database. The below bean code demonstrates how these method might be employed on a Customer CMP entity bean.

BMP : Bean-Managed Persistence


A BMP bean is an entity bean that synchronizes its state with the database manually. In other words, the bean developer must code explicit database calls into the bean itself. BMP provides the bean developer with more flexibility in the how the bean reads and writes its data than a container-managed persistence (CMP) bean. CMP bean is limited to the mapping facilities provided by the EJB vendor, BMP beans are only limited by skill of the bean developer. The ability to code an entity bean's persistence logic explicitly is important when the EJB container's CMP features are insufficient to meet the needs of the entity bean. Entity beans

that need to synchronize their state with several data sources are excellent candidates for BMP. So are beans that need to access to data sources (possibly legacy systems) that are not supported by CMP. In addition, BMP bean are often employed when a vendors CMP facilities are not sophisticated enough to handle complex Object-to-Relational mapping. The BMP bean manages its own persistence, but relies on the container to coordinate its reads and writes so that persistence is accomplished in a transactional safe manner. Coordination with the container is accomplished through two mechanisms: The persistence callback methods (ejbLoad( ) and ejbStore( )); and the Environment Naming Context (EJB). The ejbLoad( ) and ejbStore( ) methods notify a bean that its time to read and write data to the database respectively. In a BMP entity bean the code for reading and writing data to the database is done within these methods. The ejbLoad( ) is called at the beginning of a transaction, just before any business methods are executed, and the ejbStore( ) is called at the end of a transaction just before its committed. This keeps the bean state in perfect synchronization with transactions being executed, without the bean developer having to explicitly manage the transactional operations. When JDBC is used to for persistence, the Environment Naming Context (ENC) is a JNDI namespace that provides the bean with access to database connections (among other things). The database connections obtained from the JNDI ENC are managed by the container, so that they are automatically enrolled in transactions and pooled. (The extent to which this is supported depends largely on the EJB vendor.) The container may also manage other data source APIs, but JDBC is standard.

BMP/CMP Differences Difference Class definition Database access calls Persistent state Access methods for persistent and relationship fields findByPrimaryKey method Container-Managed Abstract Generated by tools Represented by virtual persistent fields Required Handled by container Handled by container, but the developer must define the EJB QL queries Handled by container Bean-Managed Not abstract Coded by developers Coded as instance variables None Coded by developers Coded by developers None

Customized finder methods Select methods

Return value of ejbCreate

Should be null

Must be the primary key

Java Persistence API


Java Persistence API is the standard API used for the management of the persistent data and object/relational mapping. Java Persistence API is added in Java EE 5 platform. Every application server compatible with Java EE 5 supports the Java Persistent APIs. Java Persistence API ensures the management of persistence and object/relational mapping. These are helpful while using the JPA in the development of applications using the platform for Java EE 5. It provides O-R mapping facility to manage relational data in java application. The Java Persistence API contains the following areas:
y y y

Java Persistence API O-R mapping metadata The query language

Features of JPA: Java Persistence API is a lightweight framework based on POJO for object-relational mapping. Java language metadata annotations and/or XML deployment descriptor is used for the mapping between Java objects and a relational database. It allows the SQL-like query language that works for both static as well as dynamic queries. It also allows the use of the pluggable persistence API. Java Persistence APIs are mainly depends on metadata annotations. API includes:
y y y

Java Persistence API Metadata annotations Java Persistence query language

Advantages of JPA: Java Persistence API is build upon the best ideas from the persistence technologies like TopLink, JDO and Hibernate. Java Persistence API is compatible with Java SE environment as well as Java EE and allows developers to take advantages of the standard persistence API. Persistency of data is not so easy for most of the enterprise applications because for this they require access to the relational database like Oracle 10g. It is your responsibility to update and retrieve the database by writing the code using SQL and JDBC. While several object-relational (O-R) frameworks such as JBoss Hibernate and OracleTopLink make persistence challenges

simpler and became popular. They let the java developer free from writing JDBC code and to concentrate only on the business logic. In EJB 2.x, container manage persistence (CMP) try to solve the persistence challenges but not successful completely. Persistence tier of the application can be developed in several ways but Java platform does not follow any standard that can be used by both Java EE and Java SE environment. But the Java Persistence API (JPA) part of EJB 3.0 spec (JSR-220) makes the persistence API standard for the Java platform. O/R mapping vendors like Hibernate and TopLink as well as JDO vendors and other leading application server vendors are receiving the JSR-220. Here we are describing EJB3 JPA by using the simple domain object model by an example. Working process of an EJB application using JPA:

Domain Model: While developing an enterprise application, first design the domain object model required to persist the data in the database. Domain model represents the persistence objects or entities in the database. An entity represents a row in the data. An entity may be a person, place or a thing about which you want to store the data in the database. A rich domain model includes the characteristics of all the object oriented behavior like inheritance, polymorphism and many more. While developing an enterprise application, first design the domain object model to persist the data in the database then design the database schema with the help of database designer. The figure illustrated below shows the bi-directional one-to-many relationship between the Employee and Department. The Contractor and the fulltime entities are inherited from the entity Employee.

Sample domain object model The Basics of EJB3 JPA and O-R Mapping Framework: Each of the O-R mapping framework such as Oracle TopLink provides three facilities: 1. It defines a declarative way known as O-R mapping metadata to perform O-R mapping. Most of the framework use XML to store the O-R mapping metadata. 2. An API is required to manipulate like to perform CRUD (CRUD stands for create, read, update, and delete) operations. The API allows you to persist, remove, update or retrieve the object from the database. O-R framework performs operations using the API and the O-R mapping metadata on your behalf. 3. Use of a query language for retrieving objects from the database is the proper way since improper SQL statements may result in slow down the performance of the operation performing on the database. A query language allows to retrieve the entities from the database and spares you from writing the SQL SELECT statements. EJB 3 provides a standard way to use the persistence by providing a standard O-R mapping mechanism, a way to extend EJB-QL to retrieve entities and an EntityManager API to perform CRUD operations. EJB3 Java Persistence API (JPA) standardizes the use of persistence for the Java platform by providing a standard mechanism for O-R mapping, an EntityManager API to perform CRUD operations, and a way to extend EJB-QL to retrieve entities. I'll discuss these three aspects of JPA later. Metadata Annotation in Action: Metadata annotations are first time introduced in Java SE 5.0. To make the development easy all the components of Java EE including EJB3 uses the metadata annotations. In EJB3 JPA annotation defines the objects, O-R mappings, and the relationships among them. JPA also have another option to use XML descriptor, But use of the metadata annotations make the development simpler and more efficient. Entities: An entity can be considered as a light weight persistence domain object. An entity defines a table in a relational database and each instance of an entity corresponds to a row in that table. An entity refers to a logical collection of data that can be stored or retrieved as a whole. For

example, in a banking application, Customer and BankAccount can be treated as entities. Customer name, customer address etc can be logically grouped together for representing a Customer entity. Similarly account number, total balance etc may be logically grouped under BankAccount entity. Persistence fields or persistent properties defines the persistent state of an entity. To map the entities and their relationship to the data in the relational database these entities use the objectrelational mapping. Requirements of Entity Classes: There are some requirements that an entity must follow:
y y y y y y

The class must contain either a public or a protect no argument constructor, while it can contain other constructors. The class as well as methods and persistence instance variables must not be declared as final. Use the annotation javax.persistence.Entity to annotate the class. Declare the persistence instance variables as protected, private or package-private so that they can directly accessed only by the entity class's methods. Entity class may extend the entity as well as non-entity classes or vice-versa. The class must implement the serializable interface if an entity instance is passed by value.

Persistence Fields and Properties in Entity Classes: There are two ways to access the persistent state of an entity either by instance variables or by using the JavaBeans-style properties. The fields or the properties must follow the Java language types:
y y y y y y y y y y y y y y y y y y y

Java primitive types java.lang.String Other serialization types including: wrappers of java primitive types java.util.Date java.util.Calender java.math.BigDecimal java.math.BigInteger java.sql.Time java.sql.Date java.sql.TimeStamp User-defined serializable types char[] Character[] byte[] Byte[] Enumerated types Other entities and/or collection of entities Embedded classes

Entity uses the persistent fields while mapping annotations. Annotations are applied to the entity's instance variable. On the other hand entity uses the persistence properties while mapping annotations. Annotations are applied to the entity's getter methods for JavaBeans-style properties. We can not apply mapping annotations to both fields as well as properties simultaneously in a single entity. Persistence Fields: Persistence accesses the entity class instance variables directly at runtime, if the entity class uses persistence fields. It is necessary to apply the object/relational mapping annotation on the instance variables. Persistent Properties: Entity must follow the method conventions of JavaBeans components while using the persistent properties. JavaBeans-style properties use getter and setter methods that are used after the entity class's instance variable names. There is a getter and a setter method for each persistence property. In case of a boolean property you may use isProperty instead of getProperty. Lets take an example to clarify this: Suppose an entity of type customer uses persistent property that has a private instance variable named firstName, the class defines two methods named getFirstName and setFirstName to retrieve and set the values of the instance variable. Use the following method signature for a single-valued persistent property.
y y

Type getProperty() void setProperty(Type type)

Multi-valued (Collection-valued) persistent fields and properties must use the supported Java collection interfaces without worrying whether the entity uses the persistence fields or properties. The collection interfaces may be used at the following places:
y y y y

java.util.Collection java.util.Set java.util.Map java.util.List

If the entity class uses persistent fields then the method signatures of the collection types must be one of these collection types. Suppose an entity of type customer includes a persistent property that uses a set of phone numbers then it should have the following methods: Set<PhoneNumber> getPhoneNumber() {} void setPhoneNumbers(Set<PhoneNumber>) {} The O-R mapping annotations must be applied to the getter methods. Note here that mapping annotations can not be applied to the fields or properties marked transient or annotated transient. Primary Keys in Entities:

Each entity contains a unique identity contained in the object. E.g. A customer entity has an identity that might be identified by the customer number. A primary key allows a client to be a particular entity instance. Every unique entity must be associated with a primary key. To prove its uniqueness every entity may have either a simple or a composite primary key. To denote the primary key property or field Simple primary key use javax.persistence.Id annotations. Composite primary keys must be composed of either a single persistent property or field or a set of single persistent properties or fields. Composite primary keys uses javax.persistence.IdClass and javax.persistence.EmbededId. The primary key, or the fields of the composite primary key (like property or field) must follow one of the following Java language types.
y y y y y

Java primitive types Java primitive wrapper types java.lang.String java.util.Date (the temporal type should be DATE) java.sql.Date

Floating point types are not allowed to use in primary keys. Primary Key Classes: A primary class must follow the certain rules:
y y y y y y

The class must have an access modifier as public. The class must include a public default constructor. Primary key must contain the properties of the type public or protected if property-based access is used. The class must be serialized. The class must implement the equals(Other other) and hashCode() methods. If the class has the mapping to multiple fields or properties of the entity class then the names and types of the primary key fields must match with those of the entity class.

The fields order_Id and itemId are combined together to make the primary key to uniquely identify the composite key. The code for managing composite key is shown as:

public final class ListItemKey implements Serializable{ public Interger order_Id; public int item_Id; public ListItemKey() {} public ListItemKey(Integer order_Id, int item_Id){ this.order_Id = order_Id; this.item_Id = item_Id; } public boolean equals(Object otherOb){ if(this == otherOb){ return true; } if(!otherOb instanceof ListItemKey){ return false; } ListItemKey other = (ListItemKey) otherOb; return ((order_Id==null?other.order_Id==null:order_Id.equals(other.order_Id)) &&(item_Id == other.item_Id)); } 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 defined for entity relationships like one-to-one, one-tomany, many-to-one, and many-to-many. One-to-one: When each entity instance is mapped to a single instance of another entity, then the mapping is known as one- to-one mapping. One-to-one relationships use the javax.persistence.OneToOne annotation on the corresponding persistent field or property. For Example: A reference variable in java contains the address of a single object so that there exists only one-to-one mapping between the object of the reference variable.

One-to-many: When an entity instance is related to many instances of other entities, then the relation is known as one-to-many. These types of relationships use the javax.persistence.OneToMany annotation on the corresponding field or property. For Example: A sales order may contain the order of multiple items so there is a one-to-many relationship between the sales order and the items. Many-to-many: When the multiple instances of an entity have the mapping to the multiple instances of the other entity then the mapping is said to many-to-many mapping. Many-to-many mapping relationships use the javax.persistence.ManyToMany annotation corresponding to the field or property. For Example: A college student have the admission in several courses while each course may have many students. Therefore there is many-to-many relationship between the students and the courses. Direction in Entity Relationships: A relationship can be either unidirectional or bi-directional. Unidirectional Relationship: A unidirectional relationship is a relationship in which only one of the two entities have the owing side. In unidirectional relationship only one entity can have the relationship property or field that may refer to the other. Example: In the example given above, the List_Item contains the relationship field that refers to the other entity named as Product, while the Product doesn't have any knowledge about the List_Item that refers to it. Bi-directional Relationships: A bi-directional relationship is the relationship in which both the entities have the owing side. In bi-directional relationship each entity in the relation have the relationship fields or property. Example: Suppose the Order in the above example have the knowledge about the List_Item instance it has and also suppose that the List_Item have the knowledge about what the Order it belongs to, then the relationship between them is said to be the bi-directional relation. Rules: There are some rules that each bi-directional relationship must follow:
y

y y y

You must use its owing side simply using the mappedBy element of the @OneToOne, @OneToMany, or @ManyToMany annotation of the inverse side of a bi-directional relationship. mappedBy element is used to designate the field or property in an entity. In a one-to-one bi-directional relationship, owing side is the side that contains the corresponding foreign key. In a many-to-one bi-directional relationships the many side is always the owing side of the relationship and must not define the mappedBy element. In case of many-to-many bi-directional relationships either side may be the owing side.

Queries and Relationship Direction:

Java Persistence query language navigates queries across relationships. The direction of the relationship can be determined by checking the navigation of a query from one entity to another. Example: In case of the unidirectional relationship, in the above example a query can navigate from List_Item to Product, but can not navigate from Product to List_Item. In case of the above Order and List_Item, a query can navigate in both the direction because both the entities have the bi-directional relationship. Cascade Deletes and Relationships: Entities having the relationships are dependent on other entities in the relationship. Lets take the above example to clarify this: While deleting the order, the list item is also deleted since it is the part of the order, this is known as cascade delete relationship. Use the element cascade=REMOVE element to delete the cascade relationships specified for @OneToOne and OneToMany relationship. Example: OneToMany(cascade=REMOVE, mappedBy="customer") public Set<Order>getOrders() { return order; } Entity Inheritance: Entities also supports the various features like inheritance, polymorphic queries, and polymorphic associations. Moreover they can also be the non-entity classes, while the non-entity classes can also extend the entity classes. These entity classes can be of the type either concrete or abstract. Abstract Entities: An abstract class can be defined as entity simply by declaring the class with the @Entity. The difference between the abstract and the concrete entities is that the concrete entities can be instantiated while the abstract entities can not. Concrete entities are queried same as the abstract entities. Suppose a query makes the target to an abstract entity then the query operates on all the concrete subclasses of the abstract entity. @Entity public abstract class Student{ @Roll_no protected Integer StudentRoll_no; ............ }

@Entity public class FullTimeStudent extends Student{ public Integer fee; ............ } @Entity public class PartTimeStudent extends Student{ protected Float classTime; } Mapped Superclasses: We can inherit the entities from their superclasses containing the persistence state and the mapping information but are not entities. The super class does not need to decorate with the @Entity annotation, and does not map as an entity by the Java Persistence provider. These superclasses are used in most of the cases when the multiple entity classes have the common state and mapping information. Mapping superclasses are declared simply by specifying the class with the javax.persistence.MappedSuperclass annotation. @MappedSuperclass public class Student{ @Roll_no protected Integer StudentRoll_no; ............ } @Entity public class FullTimeStudent extends Student{ protected Integer fee; ..................

} @Entity public class PartTimeStudent extends Student{ protected Float classTime; ............. } We can not query the mapped superclasses and can also neither be used in Query operations nor EntityManager. But use the entity subclasses of the mapped superclasses to perform the Query operations or EntityManager. Entity relationship can not target to the mapped superclasses. Mapped superclass can be either of concrete or abstract type and also don't have any corresponding table in the underlying database. Entities inherited from the mapped superclasses define the table-mapping. For instance the above code snippet contains the underlying table FULLTIMESTUDENT and PARTTIMESTUDENT but did not have any STUDENT table. Non-Entity Superclasses: As discussed above that the entities may have non-entity superclasses and these superclasses can either be abstract or concrete. The state of the non-empty superclasses and any state inherited from these superclasses are not persistent. Non-entity superclasses can be used either in Query operations or in EntityManager. While the non-entity superclasses ignore any mapping or relationship annotations. Entity Inheritance Mapping Strategies: There is a way to configure the mapping between the underlying datastore and the inherited entities simply by decorating the parent class in the hierarchy with the javax.persistence.Inheritance annotation. Entities uses three types of mapping strategies to map the entity data to the underlying database.
y y y

A table for each concrete entity class. A single table for each class hierarchy. A "join" strategy for the specific fields or properties to a subclass are mapped to different tables rather than the fields that are common to the parent class.

You can configure the strategy simply by setting the "strategy" element of @Inheritance to one of the options defined in the javax.persistence.InheritanceType enumerated type: public enum InheritanceType{ SINGLE_TABLE, JOINED, TABLE_PER_CLASS }; InheritanceType.SINGLE_TABLE is the default strategy value and is used in such situations where @Inheritance annotation is not specified in the parent class of the hierarchy.

Single Table per Class Hierarchy Strategy: This strategy corresponds to the default InheritanceType.SINGLE_TABLE, a single table in the database is mapped to all the classes in the hierarchy. This table includes a column containing a value to identify the subclass that belongs to the row represented by the instance. This column is known as discriminator column and can be specified by the javax.persistence.DiscriminatorColumn annotation at the root in the class hierarchy of the entity. The javax.persistence.DiscriminatorType enumerated type is used to set the type of the discriminator column in the database simply by setting the discriminatorTypeelement of @DiscriminatorColumn to one of the defined types. DiscriminatorTypeis defined as: public enum DiscriminatorType{ STRING, CHAR, INTEGER }; While @DiscriminatorColumn in not specified at the root of the entity hierarchy and the discriminator column is required then the persistence provider assumes the coulumn type as DiscriminatorTypeSTRING and column name as DTYPE by default.

You might also like