Java Persistence API Maciej Adamiak. Agenda -Entity, -Entity Operations, -Query Language.

Slides:



Advertisements
Similar presentations
V 6, Mats Strandberg ORM With Hibernate.
Advertisements

Copyright ©2010 Oracle Corporation Made available under Creative Commons Attribution-Share Alike 3.0 Unported EclipseLink Runtime Architecture Data Source.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Apache Struts Technology
Spring, Hibernate and Web Services 13 th September 2014.
Session-02.
Web Applications Basics. Introduction to Web Web features Clent/Server HTTP HyperText Markup Language URL addresses Web server - a computer program that.
Emmanuel Cecchet et al.  Performance Scalability of J2EE application servers.  Test effect of: ◦ Application Implementation Methods ◦ Container Design.
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
Phil Brewster  One of the first steps – identify the proper data types  Decide how data (in columns) should be stored and used.
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
Rice KRAD Data Layer JPA Design Eric Westfall July 2013.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
Maven for building Java applications By Nalin De Zoysa
1 Lecture 17 George Koutsogiannakis/SUMMER 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
DBMS Lecture 9  Object Database Management Group –12 Rules for an OODBMS –Components of the ODMG standard  OODBMS Object Model Schema  OO Data Model.
ASP.NET Programming with C# and SQL Server First Edition
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
IS-907 Java EE JPA: Simple Object-Relational Mapping.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Object persistence with Hibernate in Decision Deck 1.1 Gilles Dodinet 2 nd Decision Deck Workshop 2008, February.
Database Technical Session By: Prof. Adarsh Patel.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
Container-Managed Persistence (CMP) Entity Beans Lesson 3A / Slide 1 of 42J2EE Server Components Objectives In this lesson, you will learn to: Identify.
What is MOF? The Meta Object Facility (MOF) specification provides a set of CORBA interfaces that can be used to define and manipulate a set of interoperable.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
1 Persistence in Java Enterprise Container Managed Persistence Application Managed Persistence Michael Brockway Sajjad Shami CG0165: Advanced Applications.
Chapter 38 Persistence Framework with Patterns 1CS6359 Fall 2011 John Cole.
Oct * Brad Tutterow. VS 2008.NET 3.5LINQ Entity Framework  The ADO.NET Entity Framework is part of Microsoft’s next generation of.NET technologies.
Efficient RDF Storage and Retrieval in Jena2 Written by: Kevin Wilkinson, Craig Sayers, Harumi Kuno, Dave Reynolds Presented by: Umer Fareed 파리드.
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Java Persistence API v1.0 a standard for ORM frameworks and POJO based Persistence Magnus Larsson
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
JPA The New Enterprise Persistence Standard Mike Keith
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
1 Entity Callbacks and Listeners When you execute EntityManager methods like persist( ), merge( ), remove( ), and find( ), or when you execute EJB QL queries,
ORM Basics Repository Pattern, Models, Entity Manager Ivan Yonkov Technical Trainer Software University
CSC314 DAY 8 Introduction to SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall SQL OVERVIEW  Structured Query Language  The.
MICROSOFT ACCESS – CHAPTER 5 MICROSOFT ACCESS – CHAPTER 6 MICROSOFT ACCESS – CHAPTER 7 Sravanthi Lakkimsety Mar 14,2016.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
Hibernate Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
OOPSLA Lab1 Chapter 7 Java Binding Prof. Hyoung-Joo Kim OOPSLA Lab. Dept. of Computer Engineering Seoul National University.
CSC314 DAY 9 Intermediate SQL 1. Chapter 6 © 2013 Pearson Education, Inc. Publishing as Prentice Hall USING AND DEFINING VIEWS  Views provide users controlled.
Introduction to Database Programming with Python Gary Stewart
Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
Don't Know Jack About Object-Relational Mapping?
Chengyu Sun California State University, Los Angeles
Entity Bean Chuyên đề Lập trình Java & J2EE Chương 15
Advanced Java Programming
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Developing and testing enterprise Java applications
CS4961 Software Design Laboratory Understand Aquila Backend
Chengyu Sun California State University, Los Angeles
INTRODUCTION A Database system is basically a computer based record keeping system. The collection of data, usually referred to as the database, contains.
Presentation transcript:

Java Persistence API Maciej Adamiak

Agenda -Entity, -Entity Operations, -Query Language

ORM POJO Persistence provider Persistence storage Persistence provider

JPA in an enterprise class application Presentation Layer JSP JSF HTML/JS … Business Logic Layer EJB Spring … Persistence Layer JPA Storage / Database Oracle DB, MySQL, H2, …

OpenJPAEclipseLinkHibernateDataNucleus… Providers

Entity EntityManager EntityManagerFactory Persistence Context Metamodel JPA

Definition Example EntityManagerFactory EntityManagerFactory interface is used by the application to obtain an application - managed entity manager. When the application has finished using the entity manager factory, and/or at application shutdown, the application should close the entity manager factory. Once an entity manager factory has been closed, all its entity managers are considered to be in the closed state.

Create a new Maven project or create a JPA project (advanced) hibernate-entitymanager, h2 or mysql connector (advanced), Add dependencies: Define the persistance-unit as UL_JPA Provider: org.hibernate.ejb.HibernatePersistence Properties: hibernate.connection.url=jdbc:h2:./JpaExampleDB hibernate.dialect=org.hibernate.dialect.H2Dialect hibernate.connection.driver_class=org.h2.Driver Create src/main/resources/META-INF/persistence.xml file EntityManagerFactory emf = Persistence.createEntityManagerFactory("UL_JPA"); Create an EntityManager in main to test your configuration Exercise I - Configuration

An entity is a lightweight persistent domain object. The primary programming artifact is the entity class. An entity class may make use of auxiliary classes that serve as helper classes or that are used to represent the state of the entity. The entity class is a top-level non-final class. An enum or interface must not be designated as an entity. The entity class must be annotated with the Entity annotation or denoted in the XML descriptor as an entity. The entity class must have a no-arg constructor. The entity class may have other constructors as well. The persistent state of an entity is represented by instance variables, which may correspond to Java-Beans properties Entity

Common Entity The Id annotation specifies the primary key property or field of an entity. The Id annotation may be applied in an entity or mapped superclass. The field or property to which the Id annotation is applied should be one of the following types: any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date; java.sql.Date; java.math.BigDecimal; The Column annotation is used to specify a mapped column for a persistent property The...To... annotations define a single/multiple-valued association to another entity that has...-to-... multiplicity. It is not normally necessary to specify the associated target entity explicitly since it can usually be inferred from the type of the object being referenced. If the relationship is bidirectional, the mappedBy element must be used to specify the relationship field or property of the entity that is the owner of the The Inheritance annotation defines the inheritance strategy to be used for an entity class hierarchy. It is specified on the entity class that is the root of the entity class The JoinColumn annotation is used to specify a column for joining an entity association or element collection. The name annotation element defines the name of the foreign key column. The remaining annotation elements (other than referencedColumnName) refer to this column and have the same semantics as for the Column annotation

Exercise II – creating a domain model POI, AltitudePoint, PathNode Car POI, AltitudePoint, PathNode Car Layer Polygon (Area) UrbanArea, GreenArea... Polygon (Area) UrbanArea, GreenArea... View Line

Definition Example EntityManager An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager interface defines the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find persistent entities by primary key, and to query over persistent entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be colocated in their mapping to a single database.

Definition Example Transaction Depending on the transactional type of the entity manager, transactions involving EntityManager operations may be controlled either through JTA or through use of the resource-local EntityTransaction API, which is mapped to a resource transaction over the resource that underlies the entities managed by the entity manager. An entity manager whose underlying transactions are controlled through JTA is termed a JTA entity manager. An entity manager whose underlying transactions are controlled by the application through the EntityTransaction API is termed a resource-local entity manager. A container-managed entity manager must be a JTA entity manager. JTA entity managers are only specified for use in Java EE containers. An application-managed entity manager may be either a JTA entity manager or a resource-local entity manager. An entity manager is defined to be of a given transactional type— either JTA or resource-local—at the time its underlying entity manager factory is configured and created. Both JTA entity managers and resource-local entity managers are required to be supported in Java EE web containers and EJB containers. Within an EJB environment, a JTA entity manager is typically used. In general, in Java SE environments only resource-local entity managers are supported.

void persist(Object entity); Make an instance managed and persistent. T merge(T entity); Merge the state of the given entity into the current persistence context. void remove(Object entity); Remove the entity instance. T find(Class entityClass, Object primaryKey); Find by primary key. Search for an entity of the specified class and primary key. If the entity instance is contained in the persistence context it is returned from there. T getReference(Class entityClass, Object primaryKey); Get an instance, whose state may be lazily fetched. The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open. Query createQuery(String qlString); Create an instance of Query for executing a Java Persistence query language statement. Entity operations

Persist a Point in the DB Find a persisted Point Update found Point Delete updated Point Exercise III – entity operations

Definition Example MetaModel / Canonical Metamodel Java Persistence criteria queries are based on a metamodel of the managed classes of the persistence unit. Static metamodel classes corresponding to the managed classes of the persistence unit can be generated by means of an annotation processor or can be created by the application developer, or the metamodelcan be accessed dynamically by use of thejavax.persistence.metamodel.Metamodel interface. The getMetamodel method of the EntityManagerFactory or EntityManager interface can be used to obtain a Metamodel instance. For each managed class X in package p, a metamodel class X_ in package p is created. The name of the metamodel class is derived from the name of the managed class by appending "_" to the name of the managed class. The metamodel class X_ must be annotated with the javax.persistence.Static- Metamodel annotation. If class X extends another class S, where S is the most derived managed class (i.e., entity or mapped superclass) extended by X, then class X_ must extend class S_, where S_ is the metamodel class created for S. For every persistent non-collection and collection-valued attribute y declared by class X, where the type of y is Y, the metamodel class must contain a declaration.

The Java Persistence query language is a query specification language for string-based dynamic queries and static queries expressed through metadata. It is used to define queries over the persistent entities defined by this specification and their persistent state and relationships. The Java Persistence query language can be compiled to a target language, such as SQL, of a database or other persistent store. This allows the execution of queries to be shifted to the native language facilities provided by the database, instead of requiring queries to be executed on the runtime representation of the entity state. As a result, query methods can be optimizable as well as portable. The query language uses the abstract persistence schema of entities, including their embedded objects and relationships, for its data model, and it defines operators and expressions based on this data model. It uses a SQL-like syntax to select objects or values based on abstract schema types and relationships. It is possible to parse and validate queries before entities are deployed. JPQL I

JPQLTask SELECT e FROM Employee eSelect all employee entities SELECT li from Order o inner join o.lineItems li SELECT li from Order o IN(o.lineItems) li Get all orders lineitems SELECT c FROM Customer c LEFT OUTER JOIN FETCH c.orders Select all customers and fetch their orders. If Collection in Customer has been select s from Student s where s.score = (select max(s1.score) from Student s1) Return the Student having highest score JPQL II In BNF: select_statement :: = select_clause from_clause [where_clause] [groupby_clause] [having_clause] [orderby_clause] In BNF: select_statement :: = select_clause from_clause [where_clause] [groupby_clause] [having_clause] [orderby_clause] Path

Definition Example Criteria API The javax.persistence.criteria API interfaces are designed both to allow criteria queries to be constructed in a strongly-typed manner, using metamodel objects to provide type safety, and to allow or string-based use as an alternative. A CriteriaQuery object is created by means of one of the createQuery methods or the createTupleQuery method of the CriteriaBuilder interface. A CriteriaQuery object is typed according to its expected result type when the CriteriaQuery object is created. A TypedQuery instance created from the CriteriaQuery object by means of the EntityManager createQuery method will result in instances of this type when the resulting query is executed. The following methods are provided for the creation of CriteriaQuery objects: CriteriaQuery createQuery(Class resultClass); CriteriaQuery createTupleQuery(); CriteriaQuery createQuery();

Create a list of more than 100 PointsPersist the list using the EntityManager A. Use em.getResultList() to get the query result. B. Use em.getSingleResult() to get the query result. Find all points that have x > 10 and y < 50 Exercise III – entity operations

Create a console application. Give the user a possibility to manage different types of map/plan elements Create, Delete, Remove, Update and compose them in layers. Use JPA to persist data. Add a command to display the report content of each created layer. Tips: Use Apache CLI or a Scanner object to create a console application, Use Factory design pattern to create object from console parameters, Use Command design pattern to create CRUD operations. Use DAO pattern for persistence. Final Exercise

Bibliography Pro JPA 2; Mike Keith, Merrick Schincariol Head First: Design Patterns; Eric Freeman, Elisabeth Freeman JSR 317: JavaTM Persistence API, Version 2.1