Abstract

A Brief Introduction to Persistence API & Abstract

Department of Computer Science & Engineering Complex applications make frequent use of an underlying data model. In development, a lot of effort is put toward the mundane tasks of coding CRUD (Create-Retrieve-Update-Destroy). Data abstraction Christopher M. Bourke layers and frameworks have freed developers from needing to worry [email protected] about loading, persisting, and managing data, keeping them closer to the application layer. The Java Persistence API (JPA) is one such framework. We will give an introduction to the basic concepts and use of JPA using Hibernate.

Java Persistence API A Simple Database

Java Persistence API (JPA) is a framework for managing relational data

I Provides an abstract data layer between a database and Plain Old Java Objects

I API ( javax.persistence ) provides methods for querying and managing data

I JPQL (Java Persistence Query Language) – an SQL-like query language

I Built on top of JDBC

I JPA 1.0 (May 2006)

I JPA 2.0 (Dec 2009) Figure: Database to support course enrollments I Intended to replace heavy-weight EJB entity beans

JDBC CRUD JPA CRUD: Automated For Us!

Using JPA: Using JDBC: I We can annotate our java classes to map them to tables, columns

I Need to manage our own connections I (Alternatively: all relations can be enumerated in an XML

I Need to pull and handle each record column by column configuration file)

I Need to join or make additional queries to pull related objects I Basic CRUD is taken care of for us EntityManager I Lots of boiler-plate CRUD I An handles loading and persisting to the database

I Let’s take a look at an example... I JPQL is standardized and makes queries platform independent I Now we can just use objects instead of worrying about loading and saving them! Outline Setup

I Hibernate (Red Hat)

I Setup I Free, GPL 2.1

I Configuration: persistence unit(s) I http://hibernate.org/ I Class annotations I Alternatives: I Using JPA: the EntityManager and JPQL I OpenJPA (Apache, http://openjpa.apache.org/) I Other frameworks, jOOQ: http://www.jooq.org/

I Let’s take a look...

Persistence Until Configuration Class annotations

I @Entity - makes a POJO into a JPA entity I A persistence unit is a data source configuration I Note: JPA Entities are expected to be serializable I Defined in persistence.xml configuration file I @Table(name="..." - maps the object to a schema/table in the I Defines configuration such as database URL, login, JDBC driver, etc. database I Object Relational Mapping (ORM) can be configured here or via I @Column(name="..."), nullable=false) annotations I @Id - identifies which field is the primary key (optional) I Let’s take a look at an example... I @GeneratedValue(strategy=GenerationType.AUTO)

Join Annotations Loading

I @OneToOne

I @ManyToOne I JPA supports two loading strategies: LAZY (hibernate default) and I @OneToMany EAGER

I @ManyToMany I Eager fetching will completely load an entity and its related entities

I JPA relations are uni-directional; need to explicitly define any even if you don’t need them bi-directional relationships I Lazy fetching only loads an entity when its needed (when you get a

I “Many” is implemented via java.util.Set interface field) I Example: @ManyToOne(fetch=FetchType.LAZY) I @JoinColumn - allows you to specify which column should be used to join

I Many-to-many requires a @JoinTable specification Other Annotations & Issues Using JPA in Java

Basic JPA usage pattern: I @Transient – identifies a non-persistent field (JPA will ignore) I Create an EntityManagerFactory (automatically loads a persistence I JPA works through reflection unit from the persistence.xml config file) I Requires an available default (no-arg) constructor I Create an EntityManager from the EMF I Hibernate is a particular implementation of JPA (with Hibernate-specific features added on) I Start a transaction

I Hibernate only throws runtime exceptions, but still good practice to I Use the entity manager to load, update, persist JPA Entities try-catch-finally I Rollback or commit the transaction

I Close entity manager(s), factories

Using an Entity Manager Java Persistence Query Language

EntityManager em= ...

I em.find(Class c, Object o) – loads an entity from the database I JPA provides an SQL-like query language: JPQL

I em.persist(Object o) – Persists the object to the database I Still provides a NativeQuery interface for regular SQL (update or insert) I Allows you to refer to Objects rather than tables I em.detach() – Removes the entity from the entity manager

I em.merge() – reloads the entity with values from the database 1 String query= "FROM StudentEntity se WHERE se.nuid = :nuid"; (overwriting any in-memory changes) 2 ... 3 StudentEntity se=(StudentEntity) em.createQuery(query) I em.flush() – synchs up the database with all managed entities 4 .setParameter("nuid", myNUID) (saves all) 5 .getSingleResult(); I em.remove(Object o) – deletes the entity from the database

I em.refresh(Object o) – syncs up the object with the database

Handling InheritanceI Handling InheritanceII

JPA supports several strategies for modeling inheritance Illustrative example for Single Table Mapping strategy: unl.cse.employee I Single Table Mapping ( InheritanceType.SINGLE_TABLE ) – One table corresponds to all subclasses. Every record has every possible To discriminate which class a record corresponds to, we need a state (even if it is not used in a subclass) DiscriminatorColumn InheritanceType.JOINED I Joined ( ) – Additional state provided in I Column defined in the superclass subclasses is provided in a separate table; a subclass instance is I DiscriminatorType can be STRING , CHAR , or INTEGER (or you generated by joining all the way up the inheritance hierarchy (multiple can allow the provider to choose) inserts/deletes/updates are also needed) I Subclasses can define DiscriminatorValue I Table Per Class ( InheritanceType.TABLE_PER_CLASS ) - One table is defined for each class in the hierarchy; common state is repeated in I Subclasses can have additional annotations for subclass state each table Handling InheritanceIII JPA Advantages & Disadvantages

Additional advantages Good resources: I Closer to OOP I http: I Portable across application servers, persistence products //openjpa.apache.org/builds/1.0.4/apache-openjpa-1.0.4/ docs/manual/jpa_overview_mapping_inher.html I Can be configured to provide connection pooling, caching, etc. I http: Disadvantages //openjpa.apache.org/builds/1.0.2/apache-openjpa-1.0.2/ docs/manual/jpa_overview_mapping_discrim.html I Slight performance hit (due to reflection, auto-generated queries) I Resource hog

I Good design needs a clean object-database mapping

References & Resources

I Hibernate Download: http://www.hibernate.org/downloads.html

I Sun JPA Tutorial: http: //java.sun.com/javaee/5/docs/tutorial/doc/bnbpz.html

I Another JPA Tutorial: http://schuchert.wikispaces.com/JPA+ Tutorial+1+-+Getting+Started

I Using JPA in : http://wiki.eclipse.org/EclipseLink/Examples/JPA