You are on page 1of 20

Introduction to the Java Persistence

API (JPA) 1.0

Edem Morny
Genkey Africa Ltd
What are we discussing?
● Justification and history of Java O/R Mapping
● JPA and current implementations
● The Persistence Unit
● Entity
● Mapping relationships
● The EntityManager
● Cascades
● Etc
Justification and History of O/R
● Imagine trying to design the underlying model for a
– School
– Student
– Course etc.
● Imagine thinking in terms of classes and not in terms of
how they map to a database structure.
● Object/Relational Mapping
– Hibernate, JDO,
– Recent convert : .Net Entity Framework
JPA 1.0 and Current Implementations
● JPA 1.0 released with JEE 5
– Heavily influenced by Hibernate
● Current JPA Persistence Providers are
– Hibernate(JBoss)
– Ibatis
– TopLink(Oracle)
– EclipseLink (IBM)
The Persistence Unit Persistence
<persistence version="1.0" ....> provider

<persistence-unit name="jpaexamplePU" … >

<class>org.jaccra.jpaexample.School</class> Entities

<property name="hibernate.connection.username" value="edem"/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/jaccra"/> Db
</properties> configuration
details etc
Annotations JPA Managed Entity
public class School implements Serializable {
private Long id;
private String name;
private String address; JavaBean

public String getId() …

public void setId(Long id) ...
JPA Managed Entity - Annotations

public class School implements Serializable {

private Long id;
private String name;
@Id@GeneratedValue(strategy = GenerationType.AUTO)

public String getId() …


public String getName() ...

Mapping Relationships
● Supports definition of RDBMS relationships and is
expressed through annotations
– Single-valued :@OneToOne
– Multi-valued
● @ManyToOne
● @ManyToMany
– Supports both join tables and non-join table
● Expressed through any Collection i.e. Set or List, as
well as using a Map.
Mapping Relationships - Annotations

public class Student implements Serializable {

private School school;

public School getSchool() {
return school;
Mapping Relationships - Annotations

public class School implements Serializable {

private List<Student> students;

@OneToMany(mappedBy = "school")
public List<Student> getStudents() {
return students;
The EntityManager
● Liason between your objects and the persistence
● It enables us to in a safe way
– Save new objects (persist)
– Update existing objects (merge)
– Delete persistent object (remove)
– Find persistent objects (find)
– Query persistent object for single objects,
Collections and scalar results.
– etc.
The EnityManager -Continued To get an
EM, you
EntityManagerFactory emf = need to ask
Persistence.createEntityManagerFactory("jpaexamplePU"); from the
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction(); Start a
try{ transaction
on the EM
School school = new School();
em.persist(school); Commit the
School school = em.find(School.class,Long(1));
Find objects
System.out.println('The name of the school is: '+school.getName());
● Defines actions to be taken when changes are made
to objects related to each other
● Cascade types
@OneToMany(mappedBy = "school", cascade =
public List<Student> getStudents() {…
● In the above cascade, if any school object is deleted,
all it's orphaned students will be deleted.
Query your model – JPA QL
● Enables us to express in object terms what we want
to fetch from persistence.
● Allows the passing of parameters to such
● Provides optimisation of queries through preloading
● Enables us to fetch an object, a Collection or scalar
results as well as all types of joins.
JPA QL - Continued
● Simple query – to select a school by name 'MEST'
Query q = em.createQuery("Select s from School s where = 'MEST'")
● Same query with parameters
Query q = em.createQuery("Select s from School s where =
:name").setParameter("name", "MEST");
● Expecting only one result?
School school = (School) q.getSingleResult();
● Or a collection?
List<School> schools = q.getResultList();
● Or a scalar result
Long count = (Long) em.createQuery("Select count(s) from School
JPA QL - Continued
● Projection – Returns a list containing Object[]
Select s from School s , st from Student st
● Joins
Select s from School s join s.students st where'Francis';
● Subselects
● Advanced querying: Group by, order by etc,
● Etc
JPA – Other Features
● Embeddable classes
● Inheritance and Polymorphism
● Override annotations with XML
● Native SQL invocation
● Locking : Optimistic and Persismistic
The Future - JPA 2.0 (JSR 317)
● Currently at Proposed Final Draft stage
● Features proposed in specification
– Metamodel API (for spec implementors)
– Integration with Bean Validation (JSR 303)
– Criteria Query API
– Many many more annotations
● @Access, @OrderBy, @MapKeyClass, @Cacheable
– And a whole bunch of improvements to JPA 1.0
Further references
● Enterprise JavaBeans, v. 3.0. Java Persistence API.
● JSR-307: JPA 2.
● JSR-303: Bean Validation.
● JDBC 4.0 Specification.
● Java Persistence with Hibernate – Manning Publishers
The End