0% found this document useful (0 votes)
78 views5 pages

01IntroToJPA 2.0 Handout

The document discusses persistence using Java Persistence API (JPA) 2.0. It introduces relational databases and object-relational mapping (ORM) which allows data to be stored and accessed as objects rather than tables. JPA provides a standard way to map objects to relational databases and handles common tasks like transactions. It allows developers to work with plain Java objects rather than complex data access objects and SQL, improving productivity.

Uploaded by

Smaali Achraf
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views5 pages

01IntroToJPA 2.0 Handout

The document discusses persistence using Java Persistence API (JPA) 2.0. It introduces relational databases and object-relational mapping (ORM) which allows data to be stored and accessed as objects rather than tables. JPA provides a standard way to map objects to relational databases and handles common tasks like transactions. It allows developers to work with plain Java objects rather than complex data access objects and SQL, improving productivity.

Uploaded by

Smaali Achraf
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Persistence

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


Relational databases

Persistence using provide persistent storage of data which are organized as rows in
tables connected via PK/FK values

JPA 2.0 RDBMS guarantee ACID properties of DB transactions


Atomicity, Consistency, Isolation, Durability
Java
Design and develop using object-orientation
Objects are transient and exist in RAM
Software Applications
Object-Oriented
Access and manipulate information that is persistent
Rely on services provided by RDBMS

Monday, February 1, 2010 1 Monday, February 1, 2010 2

JDBC ORM
CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


Object-relational mapping (ORM)
Java Database Connectivity (JDBC) Convert data between incompatible systems:
Java API for connecting programs written in Java to the data in RDB: data organized as rows in tables
relational databases. OOP languages like Java: objects
provides a standard API for tool/database developers and makes Mapping gives an object-oriented view to developers who can
it possible to write database applications using a pure Java API. transparently use entities instead of tables
Database providers (i.e. DB2, Oracle, Derby, etc.) implement and Programmers can create their own using JDBC
extend the standard with their own JDBC drivers
Or you can use third-party tools like:
JDBC
Hibernate, iBATIS, JDO
establishes a connection with a database
ADO.NET Entity Framework (Microsoft)
sends SQL statements
EclipseLink, etc...
processes the results
Java Persistence API (JPA)

Monday, February 1, 2010 3 Monday, February 1, 2010 4


CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge
JPA Advantages

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


POJO persistence
Java Persistence API... quote from Sun/Oracle: ORM is completely metadata-driven
“The Java Persistence API provides a POJO persistence model for No complex data access objects (DAO).
object-relational mapping. [JPA] was developed by the EJB 3.0 The API helps you manage transactions.
software expert group as part of JSR 220, but its use is not limited
to EJB software components. It can also be used directly by web Write standards-based code that interacts with any
applications and application clients, and even outside the Java EE relational database, freeing you from vendor-specific
platform, for example, in Java SE applications.” code.
JPA facilitates use of POJOs as entity beans and Can avoid SQL in preference to a query language that
significantly reduces the need for complicated uses your class names and properties.
deployment descriptors and extra helper beans You can also use the Java Persistence API for desktop
application persistence -- not just enterprise apps.

Monday, February 1, 2010 5 Monday, February 1, 2010 6

JPA JPA concepts


CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


Entity: an application-defined object with the following
JPA maps objects to a database through metadata.
characteristics
Associated with every entity is metadata that describes
it can be made persistent
the mapping. it has a persistent identity (i.e. a key)
Metadata can be written in two different formats: it’s partially transactional... that is: an entity is created, updated
Annotations: The code of the entity is directly annotated with all and deleted within a transaction. However, in-memory entities
sorts of annotations described in the javax.persistence package. can be changed without the changes being persisted
XML descriptors: Instead of (or in addition to) annotations, you it’s not a primitive, a primitive wrapper, or built-in object
can use XML descriptors. The mapping is defined in an external Entity metadata: describes every entity
XML file that will be deployed with the entities.
can be specified via annotations or in an XML file
This can be very useful when database configuration changes depending
on the environment, for example. Entity manager: enables API calls to perform operations
Configuration by Exception: Use additional annotation on an entity
only if default mapping rules are not adequate. Until an entity manager is used to create, read, or write an entity,
the entity is just a regular nonpersistent Java object.
Monday, February 1, 2010 7 Monday, February 1, 2010 8
CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge
Entities and Relationships Example...

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


The Entity-Relationship Model has been around since Two major entities in team sports: teams and players
1975... by Peter Chen.
Teams consist of players
Entities are the objects or things in the model
Although individual players belong to only one team, a team
Relationships are the connections or links between entities consists of multiple players
JPA requires that you identify the classes of those objects The relationship between Team and Player is 1-to-M
that you will store in a database. One team has many players
Use the annotation Entity to define classes that it will map to a You could just as easily say that Player and Team have a M-to-1
relational database. relationship if you consider the relationship from a player's
Relationships have cardinality constraints perspective.
Use the annotations OneToOne, OneToMany, ManyToOne, and The M-to-1 relationship is often the reverse perspective of a 1-to-M
relationship
ManyToMany to define relationships among entities.

Monday, February 1, 2010 9 Monday, February 1, 2010 10

Annotation by Exception Primary Keys


Simple PK
CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


All annotations have default behavior Use @Id annotation on an attribute, can be one of the typical
@Entity: name of entity is the same as that of the class and every scalar data types (including String, Date, and even Integer[])
property of the class becomes a field of the entity Use @GeneratedValue to have the value of the PK be generated
Can override the default behavior by additional automatically by the persistence provider

annotations Composite PK -- two ways to annotate it


@Entity(name="SportsTeam") @EmbeddedId (recommended): create a Java class for the PK
@Table(name="tbl_sports_team") annotated with @Embeddable and then create a field of this type
in the Entity annotated with @EmbeddedId
@Column(name="last_name", length="50")
Embeddable objects don't have a persistent identity on their own; they
You can annotate the fields or the properties can be embedded only within owning entities.
There are arguments as to which is best @IdClass: create a Java class for the PK w/no annotations, then
I recommend that you provide annotations on the fields annotate the entity with @IdClass
Whatever you do.... do not mix them! Both approaches get mapped to the same table structure
See examples in Java EE book, chapter 3.
Monday, February 1, 2010 11 Monday, February 1, 2010 12
CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge
@Column annotation Other annotations

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


@Transient
Some important defaults:
To annotate a field that is not to be persisted
name of column is the same as that of the field
null values allowed on non-primitive data types
@Access
To annotate whether FIELD or PROPERTY access type is to be
Strings have a length of 255
used... avoid using unless necessary!
Sample use...
@ElementCollection and @CollectionTable
@Column(name="first_name")
For annotating a field that is a Collection Java types
@Column(name="team_name", unique=true, length=100)
In the DB, a table will be created for the values in the collection

Monday, February 1, 2010 13 Monday, February 1, 2010 14

Relationships Annotating Relationships


CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


DB relationships can be unidirectional or bidirectional Bidirectional relationship (1-to-M and M-to-1)
Unidirectional relationships Declare a M-to-1 relationship between Player and Team entities
by adding the ManyToOne annotation to the team property of the
only one entity knows about the other entity or entities in the
Player class
relationship.
Declare a 1-to-M relationship b/w Team and Player entities by
have an "owning" side, the side that maintains the relationship in
adding the OneToMany annotation to the players property of the
the database.
Team class
Bidirectional relationships Including a mappedBy="team" element specifying that the owning side
have both an owning and an "inverse" side. of the relationship is the Player and that the team property of Player has
the mapping.
The owning side determines how and when updates
affect the relationship. Note:
There is a mappedBy element on the @OneToOne, @OneToMany,
Also, the owning side usually contains the foreign key to and @ManyToMany annotations, but not on the @ManyToOne
the other entity. annotation.

Monday, February 1, 2010 15 Monday, February 1, 2010 16


CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge
Relationship annotations Entity Manager

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


To manage entities in your persistence application, you
Important elements
need to obtain an entity manager from an
cascade: CascadeType.{MERGE,PERSIST,REFRESH,REMOVE,ALL}
specifies which operations will be propagated to the target of the
EntityManagerFactory.
relationship In the Java SE environment, the application manages the
fetch: FetchType.{LAZY, EAGER} life cycle of an entity manager -- there is no container
whether the persistence provider will automatically fetch the target of
the relationship whenever the source is retrieved
Example of creating an entity manager in Java SE
default is LAZY for 1-to-M, and M-to-M; EAGER for M-to-1 and 1-to-1 EntityManagerFactory emf =
Persistence.createEntityManagerFactory("LeaguePU");
optional: true (default) or false EntityManager em = emf.createEntityManager();
if set to false, then a non-null relationship must always exist
Now start a transaction from which to modify data
@JoinColumn em.getTransaction().begin();
Allows you to customize the join column (i.e. foreign key)
Transaction is not needed if you just query

Monday, February 1, 2010 17 Monday, February 1, 2010 18

EM API JPQL
CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge

CECS 423 Lecture on JPA 2.0 by Dr. Alvaro Monge


persist: make an instance managed and persistent
find: search for an entity of a specified class and PK
value
getReference: like find but with lazy fetch The results obtained from SQL are in the form of rows
remove: remove the entity from the persistence context and columns (tables), whereas JPQL uses an entity or a
and from the DB collection of entities.
flush: forces any changes to be flushed to the database, JPQL syntax is object oriented
otherwise they will be done at commit time of the JPQL is mapped to SQL and JDBC calls
transaction -- changes can still be rolled back.
refresh: overwrites the current state of a managed
entity with data that is in the DB

Monday, February 1, 2010 19 Monday, February 1, 2010 20

You might also like