Top Banner
Enterprise Java Jan-June 2014 Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 1 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT) Unit 6: Overview: JNDI, JMS, JPA, XML Introduction of JNDI Introduction to JMS, JMS Configuration Introduction of JPA & XML Packaging and Deploying J2EE application
24
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 1 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Unit 6: Overview: JNDI, JMS, JPA, XML

Introduction of JNDI

Introduction to JMS, JMS Configuration

Introduction of JPA & XML

Packaging and Deploying J2EE application

Page 2: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 2 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

1.0. JNDI OVERVIEW

The Java Naming and Directory Interface (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories new, emerging, and already deployed can be accessed in a common way.

Architecture The JNDI architecture consists of an API and a service provider interface (SPI). Java applications use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, thereby allowing the Java application using the JNDI API to access their services. See the following figure.

Packaging The JNDI is included in the Java 2 SDK, v1.3 and later releases. It is also available as a Java Standard Extension for use with the JDK 1.1 and the Java 2 SDK, v1.2. It extends the v1.1 and v1.2 platforms to provide naming and directory functionality.

Page 3: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 3 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

To use the JNDI, you must have the JNDI classes and one or more service providers. The Java 2 SDK, v1.3 includes three service providers for the following naming/directory services:

Lightweight Directory Access Protocol (LDAP) Common Object Request Broker Architecture (CORBA) Common Object

Services (COS) name service Java Remote Method Invocation (RMI) Registry

Other service providers can be downloaded from the JNDI Web site or obtained from other vendors. When using the JNDI as a Standard Extension on the JDK 1.1 and Java 2 SDK, v1.2, you must first download the JNDI classes and one or more service providers. See the Preparations lesson for details on how to install the JNDI classes and service providers.

The JNDI is divided into five packages:

javax.naming javax.naming.directory javax.naming.event javax.naming.ldap javax.naming.spi

1.1.NAMING PACKAGE

The javax.naming package contains classes and interfaces for accessing naming services.

Context

The javax.naming package defines a Context interface, which is the core interface for looking up, binding/unbinding, renaming objects and creating and destroying subcontexts. The most commonly used operation is lookup(). You supply lookup() the name of the object you want to look up, and it returns the object bound to that name. For example, the following code fragment looks up a printer and sends a document to the printer object to be printed.

Printer printer = (Printer)ctx.lookup("treekiller"); printer.print(report);

Page 4: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 4 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Names

Every naming method in the Context interface has two overloads: one that accepts a Name argument and one that accepts a java.lang.String name. Name is an interface that represents a generic name--an ordered sequence of zero or more components. For the methods in the Context interface, a Name argument that is an instance of CompositeName represents a composite name , so you can name an object using a name that spans multiple namespaces. A Name argument of any other type represents a compound name. (Names are covered in the Beyond the Basics trail.) The overloads that accept Name are useful for applications that need to manipulate names, that is, composing them, comparing components, and so on.

A java.lang.String name argument represents a composite name. The overloads that accept java.lang.String names are likely to be more useful for simple applications, such as those that simply read in a name and look up the corresponding object.

Bindings listBindings() returns an enumeration of name-to-object bindings. Each binding is represented by an instance of the Binding class. A binding is a tuple containing the name of the bound object, the name of the object's class, and the object itself. list() is similar to listBindings(), except that it returns an enumeration of NameClassPair. NameClassPair contains an object's name and the name of the object's class. list() is useful for applications such as browsers that want to discover information about the objects bound within a context but that don't need all of the actual objects. Although listBindings() provides all of the same information, it is potentially a much more expensive operation.

References Objects are stored in naming and directory services in different ways. A service that supports storing Java objects might support storing an object in its serialized form. However, some naming and directory services do not support the storing of Java objects. Furthermore, for some objects in the directory, Java programs are but one group of applications that access them. In this case, a serialized Java object might not be the most appropriate representation. A reference might be a very compact representation of an object, whereas its serialized form might contain a lot more state.

Page 5: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 5 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

The JNDI defines the Reference class to represent a reference. A reference contains information on how to construct a copy of the object. The JNDI will attempt to turn references looked up from the directory into the Java objects that they represent so that JNDI clients have the illusion that what is stored in the directory are Java objects.

The Initial Context In the JNDI, all naming and directory operations are performed relative to a context. There are no absolute roots. Therefore the JNDI defines an initial context, InitialContext, which provides a starting point for naming and directory operations. Once you have an initial context, you can use it to look up other contexts and objects.

Exceptions The JNDI defines a class hierarchy for exceptions that can be thrown in the course of performing naming and directory operations. The root of this class hierarchy is NamingException. Programs interested in dealing with a particular exception can catch the corresponding subclass of the exception. Otherwise, they should catch NamingException.

1.2.DIRECTORY PACKAGE

The javax.naming.directory package extends the javax.naming package to provide functionality for accessing directory services in addition to naming services. This package allows applications to retrieve attributes associated with objects stored in the directory and to search for objects using specified attributes.

The Directory Context The DirContext interface represents a directory context. It defines methods for examining and updating attributes associated with a directory object. You use getAttributes() to retrieve the attributes associated with a directory object (for which you supply the name). Attributes are modified using modifyAttributes(). You can add, replace, or remove attributes and/or attribute values using this operation. DirContext also behaves as a naming context by extending the Context interface. This means that any directory object can also provide a naming context. For example, a directory object for a person might contain attributes about that person as well as

Page 6: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 6 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

provide a context for naming objects, such as the person's printers and file system relative to that person directory object.

Searches DirContext contains methods for performing content-based searching of the directory. In the simplest and most common form of usage, the application specifies a set of attributes--possibly with specific values--to match and submits this attribute set to the search() method. Other overloaded forms of search() support more sophisticated search filters.

Page 7: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 7 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

2.0. JMS (JAVA MESSAGING SERVICES)

Messaging is a method of communication between software components or applications.

A messaging system is a peer-to-peer facility

o A messaging client can send messages to, and receive messages from, any other

client.

o Each client connects to a messaging agent that provides facilities for creating,

sending, receiving, and reading messages.

Messaging enables distributed communication that is loosely coupled.

o A component sends a message to a destination, and the recipient can retrieve the

message from the destination.

o The sender and the receiver do not have to be available at the same time in order

to communicate.

o The sender does not need to know anything about the receiver; nor does the

receiver need to know anything about the sender.

o The sender and the receiver need to know only which message format and which

destination to use.

Messaging also differs from e-mail.

o E-mail is a method of communication between people or between software

applications and people.

o Messaging is used for communication between software applications or software

components.

2.1.MESSAGE-ORIENTED MIDDLEWARE (MOM)

Message-oriented middleware is a software application or messaging agent that provides

facilities for creating, sending, receiving, and reading messages synchronously or

asynchronously between system components.

A client which produces the message is called a producer and the client which receives the

Page 8: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 8 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

message is called a consumer. All the messages sent are stored in a particular location which is

called a destination.

2.2. JMS API

The Java Message Service is a Java API that allows applications to create, send, receive, and

read messages. The JMS API defines a common set of interfaces and associated semantics that

allow programs written in the Java programming language to communicate with other

messaging implementations.

The JMS API enables communication that is not only loosely coupled but also,

Asynchronous: A JMS provider can deliver messages to a client as they arrive; a client does not

have to request messages in order to receive them.

Reliable: The JMS API can ensure that a message is delivered once and only once. Lower levels of

reliability are available for applications that can afford to miss messages or to receive duplicate

messages.

Page 9: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 9 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

2.3.JMS APPLICATION

A JMS application is composed of the following parts:

JMS Clients – These are the Java language programs that send and receive messages.

Non-JMS Clients – These are clients that use a message system’s native client API instead of JMS.

Messages – Each application defines a set of messages that are used to communicate information

between its clients.

JMS Provider – This is a messaging system (MOM) that implements JMS API in addition to the other

administrative and control functionality required of a full featured messaging product.

Administered Objects – Administered objects are preconfigured JMS objects created by an

administrator for the use of clients.

2.4.JMS ADMINISTERED OBJECTS

There are two types of JMS administered objects:

ConnectionFactory – This is the object a client uses to create a connection with a provider.

Destination – This is the object a client uses to specify the destination of messages it is sending and

the source of messages it receives.

Administered objects are placed in a JNDI namespace by an administrator.

Page 10: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 10 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

2.5.JMS MESSAGING MODELS

The JMS API supports two models:

Point-to-Point (PTP) Model

In point-to-point messaging model, a producer creates and sends a message which will be received

only by a single consumer.

In point-to-point model, the message destination is called “Queue”.

PTP characteristics,

o Each message has only one consumer.

o A sender and a receiver of a message have no timing dependencies. The receiver can fetch

the message whether or not it was running when the client sent the message.

o The receiver acknowledges the successful processing of a message.

Page 11: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 11 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Publish/Subscribe Model

In publish/subscribe model, any number of clients can subscribe to a message destination and

when a client sends (publishes) a message to the destination, that message is received by all clients

who have subscribed to that destination.

In this model, the message producer is called publisher and the consumers are called subscribers.

Also the message destination is called “Topic”.

Publish/Subscribe model characteristics,

o Each message can have multiple consumers.

o Publishers and subscribers have a timing dependency. A client that subscribes to a topic

can consume only messages published after the client has created a subscription, and the

subscriber must continue to be active in order for it to consume messages.

Page 12: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 12 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

2.6.JMS PROGRAMMING MODEL

ConnectionFactory

an administered object that encapsulates a set of connection configuration parameters.

o A client uses it to create a Connection to a JMS provider.

o JMS clients find administered objects by looking them up in a JNDI namespace.

o Connection factories come in two forms implementing either QueueConnectionFactory or

TopicConnectionFactory interfaces.

Page 13: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 13 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

At the beginning of a JMS client program, you usually perform a JNDI API lookup of the connection

factory.

For example, the following code fragment obtains an InitialContext object and uses it to look up the

QueueConnectionFactory and the TopicConnectionFactory by name. You can choose any of the

below three options based on your requirement. 01

02

03

04

05

06

07

08

09

10

Context context = new InitialContext();

//1. ConnectionFactory

ConnectionFactory connectionFactory =

(ConnectionFactory) context.lookup("ConnectionFactory");

//2. QueueConnectionFactory

QueueConnectionFactory queueConnectionFactory =

(QueueConnectionFactory) context.lookup("QueueConnectionFactory");

//3. TopicConnectionFactory

TopicConnectionFactory topicConnectionFactory =

(TopicConnectionFactory) context.lookup("TopicConnectionFactory");

Connection

encapsulates a virtual connection with a JMS provider.

Like connection factories, connections come in two forms, implementing either the

QueueConnection or the TopicConnection interface.

Page 14: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 14 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

1

2

3

4

5

6

7

8

//1. Connection

Connection connection = connectionFactory.createConnection();

//2. QueueConnection

QueueConnection queueConnection =

queueConnectionFactory.createQueueConnection();

//3. TopicConnection

TopicConnection topicConnection =

topicConnectionFactory.createTopicConnection();

A JMS client usually creates a connection, one or more sessions, and a number of message

producers.

When an application completes, you need to close any connections that you have created. Closing

a connection also closes its sessions and their message producers and message consumers. 1

2

3

connection.close();

queueConnection.close();

topicConnection.close();

Destination

A Destination object is a JMS administered object that encapsulates a provider-specific address for

storing and retrieving messages.

Destination, like session, comes in two forms, implementing either the Queue or

the Topicinterface.

Page 15: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 15 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

We use Session object to create a destination

Client uses JNDI API to look up destination. The following line of code looks up a queue and a

topic. 1

2

3

Destination destination = (Queue)context.lookup(“queue/MyQueue”);

Queue queue = (Queue)context.lookup(“queue/MyQueue”);

Topic topic = (Topic)context.lookup(“topic/MyTopic”);

Session

Session is a lightweight JMS object which acts as a single-threaded context for producing and

consuming messages. Session creates,

o Message producers,

o Message consumers,

o Messages,

o Message Destination (Queue or Topic)

Sessions, like connections, come in two forms, implementing either the QueueSession or the

TopicSession interface.

We use Connection object to create a session.

Page 16: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 16 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

1

2

3

4

5

6

7

8

//1. Session

Session session = connection.createSession(false,

Session. DUPS_OK_ACKNOWLEDGE);

//2. QueueSession

QueueSession queueSession = queueConnection.createQueueSession(false,

Session.AUTO_ACKNOWLEDGE);

//3. TopicSession

TopicSession topicSession = topicConnection.createTopicSession(true, 0);

Message

JMS application produces and consumes message.

The Message interface is the root interface of all JMS messages. There are five types of message:

BytesMessage, TextMessage, ObjectMessage, StreamMessage and MapMessage.

We use Session object to create a message

Page 17: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 17 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

1

2

3

4

5

6

TextMessage message = session.createTextMessage();

message.setText("Hello EJB3 MDB!!!");

BytesMessage byteMessage = session.createBytesMessage();

MapMessage mapMessage = session.createMapMessage();

StreamMessage streamMessage = session.createStreamMessage();

ObjectMessage objMsg = session.createObjectMessage();

MessageProducer

A message producer is an object created by a session and is used for sending messages to a

destination.

MessageProducer comes in two forms implementing either the QueueSender or the TopicPublisher

interface.

We use Session object to create a message producer.

The following snippet shows how to create a message producer, queue sender and a topic

publisher. 1

2

3

MessageProducer producer = session.createProducer(destination)

QueueSender queueSender = queueSession.createSender(queue);

TopicPublisher topicPublisher = topicSession.createPublisher(topic);

Once a message producer is created, you can use it to send messages.

1 queueSender.send(message);

Page 18: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 18 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

2 topicPublisher.publish(message);

MessageConsumer

an object created by a Session that is used for receiving messages sent to a destination.

2.7.MESSAGE DRIVEN BEAN

A message-driven bean (MDB) is an enterprise bean that allows Java EE applications to

process messages asynchronously. In other words, an MDB is anasynchronous message

consumer.

A message-driven bean is invoked by the container as a result of the arrival of a message at

the destination or endpoint that is serviced by the message-driven bean.

The messages can be sent by any Java EE component (an application client, another

enterprise bean, or a web component) or by a JMS application or system that does not use Java

EE technology.

A message-driven bean instance is created by the container to handle the processing of the

messages for which the message-driven bean is the consumer. Its lifetime is controlled by the

container.

When a message arrives, the container calls the message-driven bean’s

onMessage(Message message) method to process the message. The onMessage() method

normally casts the message to one of the five JMS message types and handles it in accordance

with the application’s business logic. The onMessage() method can call helper methods or can

invoke a session bean to process the information in the message or to store it in a database.

Page 19: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 19 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Messaging using MDB Consumer

2.8.MDB CHARACTERISTICS

Message-driven beans have the following characteristics.

They execute upon receipt of a single client message.

They are invoked asynchronously.

They are relatively short-lived.

They do not represent directly shared data in the database, but they can access and update

this data.

They can be transaction-aware.

They are stateless.

2.9.LIFECYCLE CALLBACK METHODS

The following lifecycle event callbacks are supported for message-driven beans.

PostConstruct

The PostConstruct callback occurs after the container creates a new instance of MDB and before

the first message listener method invocation on the bean. This is at a point after which any

dependency injection (DI) has been performed by the container.

Page 20: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 20 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

PreDestroy

The PreDestroy callback occurs before the bean is removed from the pool or destroyed.

The PostConstruct and PreDestroy lifecycle callback interceptor methods execute in an

unspecified transaction and security context.

2.10.MDB LIFECYCLE

When a client sends a message to a Destination for which a message-driven bean is the

consumer, the container selects one of its method-ready instances and invokes the instance’s

message listener method.

The following steps describe the life cycle of a message-driven bean instance:

A message-driven bean instance’s life starts when the container invokes newInstance on the

message-driven bean class to create a new instance.

Page 21: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 21 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Next, the container injects the bean’s MessageDrivenContext, if applicable, and performs any

other dependency injection as specified by metadata annotations on the bean class or by the

deployment descriptor.

The container then calls the bean’s PostConstruct lifecycle callback methods, if any.

The message-driven bean instance is now ready to be delivered a message sent to its associated

destination or endpoint by any client or a call from the container to a timeout callback method.

When the container no longer needs the instance (which usually happens when the container

wants to reduce the number of instances in the method-ready pool), the container invokes

thePreDestroy lifecycle callback methods for it, if any. This ends the life of the message-driven

bean instance.

Page 22: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 22 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

3. JPA (JAVA PERSISTENCE API)

The process of mapping Java objects to database tables and vice versa is called "Object-relational

mapping" (ORM). The Java Persistence API (JPA) is one possible approach to ORM. JPA is a

specification and several implementations are available. Popular implementations are Hibernate,

EclipseLink and Apache OpenJPA. The reference implementation of JPA is EclipseLink. Via JPA the

developer can map, store, update and retrieve data from relational databases to Java objects and

vice versa. JPA permits the developer to work directly with objects rather then with SQL statements.

The JPA implementation is typically called persistence provider. JPA can be used in Java-EE and Java-

SE applications. The mapping between Java objects and database tables is defined via persistence

metadata. The JPA provider will use the persistence metadata information to perform the correct

database operations. JPA typically defines the metadata via annotations in the Java class.

Alternatively the metadata can be defined via XML or a combination of both. A XML configuration

overwrites the annotations. The following description will be based on the usage of annotations. JPA

defines a SQL-like Query language for static and dynamic queries. Most JPA persistence provider

offer the option to create automatically the database schema based on the metadata.

3.1. ENTITY

A class which should be persisted in a database it must be annotated with javax.persistence.Entity. Such a

class is called Entity. JPA will create a table for the entity in your database. Instances of the class will

be a row in the table. All entity classes must define a primary key, must have a non-arg constructor

and or not allowed to be final. Keys can be a single field or a combination of fields. JPA allows to

auto-generate the primary key in the database via the @GeneratedValue annotation. By default, the table

name corresponds to the class name. You can change this with the addition to the annotation

@Table(name="NEWTABLENAME").

3.2. PERSISTENCE OF FIELDS

The fields of the Entity will be saved in the database. JPA can use either your instance variables

(fields) or the corresponding getters and setters to access the fields. You are not allowed to mix both

methods. If you want to use the setter and getter methods the Java class must follow the Java Bean

naming conventions. JPA persists per default all fields of an Entity, if fields should not be saved they

must be marked with @Transient.

Page 23: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 23 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

By default each field is mapped to a column with the name of the field. You can change the default

name via @Column(name="newColumnName").

The following annotations can be used.

Table 1. Annotations for fields / getter and setter

@Id Identifies the unique ID of the database entry

@GeneratedValue Together with ID defines that this value is generated automatically.

@Transient Field will not be saved in database

3.3. RELATIONSHIP MAPPING

JPA allows to define relationships between classes, e.g. it can be defined that a class is part of

another class (containment). Classes can have one to one, one to many, many to one, and many to

many relationships with other classes. A relationship can be bidirectional or unidirectional, e.g. in a

bidirectional relationship both classes store a reference to each other while in an unidirectional case

only one class has a reference to the other class. Within a bidirectional relationship you need to

specify the owning side of this relationship in the other class with the attribute "mappedBy",

e.g. @ManyToMany(mappedBy="attributeOfTheOwningClass".

@OneToOne

@OneToMany

@ManyToOne

Page 24: JNDI, JMS, JPA, XML

Enterprise Java Jan-June 2014

Prepared by: Mr. Hitesh Kumar Sharma & Mr. Ravi Tomar Page 24 Prepared for : B.Tech CS VI Sem (MFT+O&G+OSS+CCVT)

Table 2. Relationship annotations

3.5. ENTITY MANAGER

The entity manager javax.persistence.EntityManager provides the operations from and to the database, e.g.

find objects, persists them, remove objects from the database, etc. In a JavaEE application the entity

manager is automatically inserted in the web application. Outside JavaEE you need to manage the

entity manager yourself. Entities which are managed by an Entity Manager will automatically

propagate these changes to the database (if this happens within a commit statement). If the Entity

Manager is closed (via close()) then the managed entities are in a detached state. If synchronize

them again with the database a Entity Manager provides the merge() method. The persistence

context describes all Entities of one Entity manager.

3.6. PERSISTENCE UNITS

The EntityManager is created by the EntitiyManagerFactory which is configured by the persistence unit. The

persistence unit is described via the file "persistence.xml" in the directory META-INF in the source

folder. A set of entities which are logical connected will be grouped via a persistence unit.

"persistence.xml" defines the connection data to the database, e.g. the driver, the user and the

password,

@ManyToMany