You are on page 1of 20

Introduction to the Java Persistence

API (JPA) 1.0

Edem Morny
Genkey Africa Ltd
http://edemmorny.wordpress.com
What are we discussing?
● Justification and history of Java O/R Mapping
● JPA and current implementations
● The Persistence Unit
● Entity
● Mapping relationships
● The EntityManager
● JPA QL
● Cascades
● Etc
Justification and History of O/R
Mapping
● Imagine trying to design the underlying model for a
school.
– 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" … >


<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>org.jaccra.jpaexample.School</class> Entities

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

public String getId() …


public void setId(Long id) ...
JPA Managed Entity - Annotations
@Entity
@Table(name=”skool”)

public class School implements Serializable {


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

public String getId() …

@Column(name=”first_name”,nullable=false,length=20)

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
@Entity

public class Student implements Serializable {


private School school;

@ManyToOne
@JoinColumn(nullable=false)
public School getSchool() {
return school;
}
...
Mapping Relationships - Annotations
@Entity

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
layer.
● 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
factory
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction(); Start a
try{ transaction
on the EM
School school = new School();
school.setName("MEST");
em.persist(school); Commit the
transaction
tx.commit();
}catch....
School school = em.find(School.class,Long(1));
Find objects
System.out.println('The name of the school is: '+school.getName());
Cascades
● Defines actions to be taken when changes are made
to objects related to each other
● Cascade types
– ALL, MERGE,PERSIST,REMOVE,REFRESH
@OneToMany(mappedBy = "school", cascade =
CascadeType.ALL)
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
expressions.
● Provides optimisation of queries through preloading
NamedQueries.
● 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 s.name = 'MEST'")
● Same query with parameters
Query q = em.createQuery("Select s from School s where s.name =
: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
s).getSingleResult();
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 st.name='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. http://jcp.org/en/jsr/detail?id=307
● JSR-303: Bean Validation.http://jcp.org/en/jsr/detail?id=303
● JDBC 4.0 Specification. http://java.sun.com/products/jdbc.
● Java Persistence with Hibernate – Manning Publishers
● http://edemmorny.wordpress.com
The End