Download presentation
Presentation is loading. Please wait.
Published byAnneleen de Veen Modified over 6 years ago
1
Gastcollege Fontys, Venlo - Java Persistence API
Bert Ertman Title: Enterprise JavaBeans 3.0 – Java Persistence API [Gastcollege Fontys Hogeschool Venlo] Author: Bert Ertman, Info Support Last update: Time: 90 minutes talk Level: Beginner - Intermediate Persistence 4/3/2019
2
IT Architect at Info Support BV
About me IT Architect at Info Support BV Competence Center Java Endeavour Java Software Factory NLJUG Co-lead Frequent speaker on Java (SE/EE) and Software Architecture related topics Author for Java Magazine and Software Release Magazine Mail: Weblog: Gastcollege Fontys – Java Persistence API
3
Contents The Object/Relational paradigm mismatch
Agenda Contents The Object/Relational paradigm mismatch Goodbye Entity Beans, hello JPA! Lifecycle of an entity Developing simple entities Persistent identity (primary key) Persistence Context EntityManager API Entity life cycle callbacks Basic relational mapping … Gastcollege Fontys – Java Persistence API 4/3/2019
4
… Relationships Inheritance Queries
Agenda cont’d … Relationships Some examples Cascading operations Inheritance Table mapping strategies Queries EJB-QL Static and dynamic queries Deployment Descriptor (persistence.xml) Deploying Persistence Units Gastcollege Fontys – Java Persistence API 4/3/2019
5
The Object/Relational paradigm mismatch
Granularity Subtypes Identity Associations Object Graph Navigation Cost of the mismatch Granularity – Alles in 1 object of juist alles uitnormaliseren over meerdere tabellen? Subtypes – Overerving in Java Identity – primary key versus object handles (pointers) Associations – Lists / Collections of data Object Graph Mismatch – SQL: select * from person where firstname = ‘bert’, hoe in Java? Cost of the mismatch – Extremely efforts in writing database access layers, mapping, conversions, etc. Gastcollege Fontys – Java Persistence API 4/3/2019
6
Java Persistence API Java Persistence adds full advantage of OO while elements of the object map are persisted to the database behind the scenes Simplified entity bean programming model Improved support for domain modeling Inheritance and polymorphism Entities are POJOs Allow for entities to be used outside of the container Enhanced testability! Gastcollege Fontys – Java Persistence API
7
Standardize ORM into single Java Persistence API
Usable in both Java SE and Java EE Based on best practices from EJB 2.x, Hibernate, JDO, TopLink, etc. Enhanced testability! Support for pluggable, third-party persistence providers JPA Hibernate Persistence Provider Toplink Persistence Provider Kodo Persistence Provider … Hibernate Toplink Kodo … Gastcollege Fontys – Java Persistence API
8
Persistent objects Entities, not Entity Beans
Entities, reborn! Persistent objects Entities, not Entity Beans Java objects, not ‘components’ Concrete classes Support use of new keyword Serializable, detachable, and mergeable No more need for Transfer Objects Indicated annotation 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 no-arg constructor must be public or protected. The entity class must be a top-level class. The entity class must not be final. No methods or persistent instance variables of the entity class may be final. If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface. Entities support inheritance, polymorphic associations, and polymorphic queries. Both abstract and concrete classes can be entities. Entities may extend non-entity classes as well as entity classes, and non-entity classes may extend entity classes. The persistent state of an entity is represented by instance variables, which may correspond to JavaBeans properties. An instance variable may be directly accessed only from within the methods of the entity by the entity instance itself. Instance variables must not be accessed by clients of the entity. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods. Instance variables must be private, protected, or package visibility. Gastcollege Fontys – Java Persistence API 4/3/2019
9
Uniquely identifies entity in database
Persistent Identity Uniquely identifies entity in database Every entity must have identity Primary key! Simple field/property @Entity public class Restaurant { private long id; private String name; @Id public long getId() { return id; } // Other getters/setters go here… @Entity public class Restaurant { @Id private long id; private String name; // Getters/setters go here… } annotation is applied to a persistent field or property of an entity class or mapped superclass to denote a composite primary key that is an embeddable class. annotation is applied to an entity class or a mapped superclass to specify a composite primary key class that is mapped to multiple fields or properties of the entity. The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same. Gastcollege Fontys – Java Persistence API 4/3/2019
10
Define generator strategy type
Persistent Identity Persistence providers are required to provide key generation for primitive keys Define generator strategy type AUTO, IDENTITY, TABLE, SEQUENCE @Entity public class Restaurant { @Id @GeneratedValue private long id; private String name; // Getters/setters go here… } Gastcollege Fontys – Java Persistence API 4/3/2019
11
Synchronizing entities with the database
EntityManager API for object/relational mapping (ORM) Inject Persistence Context Set of “managed” entities (at runtime) Entities are either managed (attached) or unmanaged (detached) Gastcollege Fontys – Java Persistence API
12
Persistence Context & EntityManager API
Employee employee = new Employee(); E E employee.setName("Paul"); entityManager.persist(employee); employee.setName("Bert"); EntityManager API Persistence Context E E The EntityManagerFactory is invisble to the programmer in a Java EE environment. Entities within the PC are ‘managed entities’. Entities outside the PC are ‘unmanaged entities’. DB E E Gastcollege Fontys – Java Persistence API 4/3/2019
13
Life cycle of an Entity new () persist() refresh() persist() find ()
Managed Removed remove() merge() Persistence Context ends Detached Gastcollege Fontys – Java Persistence API 4/3/2019
14
Insert a new instance of the entity into the database
Example: Persist Insert a new instance of the entity into the database The entity instance becomes managed in the Persistence Context @PersistenceContext private EntityManager em; public Customer createCustomer(int id, String name) { Customer customer = new Customer(id, name); em.persist(customer); return customer; } Gastcollege Fontys – Java Persistence API
15
State of detached entity gets merged into a managed copy of the entity
Example: Merge State of detached entity gets merged into a managed copy of the entity merge() returns managed entity with different Java identity than detached entity @PersistenceContext private EntityManager em; public Customer storeUpdatedCustomer(Customer customer) { return em.merge(customer); } Gastcollege Fontys – Java Persistence API
16
Find on primary key EntityManager returns a managed bean Example: Find
Can also use EJB-QL queries @PersistenceContext private EntityManager em; public void setCustomerName(int customerId, String name) { Customer c = em.find(Customer.class, customerId); c.setName(name); } Gastcollege Fontys – Java Persistence API
17
Removal via EntityManager API
Removing entities Removal via EntityManager API Entities must be managed to be removed E.g. do a find() first Could also use EJB-QL query instead Will be covered later in this presentation Gastcollege Fontys – Java Persistence API
18
Entity life cycle callbacks
Entity Callbacks can be defined to receive notification of lifecycle events: @PostLoad @PostPersist public void doSomething() { System.out.println("Entity persisted!"); } Gastcollege Fontys – Java Persistence API
19
Basic relational mapping
JPA provides enough flexibility to start from either direction: Database Entities Entities Database Elementary schema mappings: Table and column mappings: @Table @Column Gastcollege Fontys – Java Persistence API
20
Example: elementary schema mapping
@Entity @Table(name="TBL_CUSTOMER") public class Customer { private long id; private String name; @Id @Column(name="CUST_ID", nullable=false, columnDefinition="integer") public long getId() { return id; } public void setId(long id) { this.id = id; @Column(name="CUST_NAME", length=40) public String getName() { return name; public void setName(String name) { this.name = name; CUST_ID CUST_NAME TBL_CUSTOMER Gastcollege Fontys – Java Persistence API
21
Common relationships supported:
Unidirectional or bidirectional Owning side of relationship can specify physical mapping @JoinColumn @JoinTable Gastcollege Fontys – Java Persistence API
22
Example: Order LineItem
One-to-Many Example: Order LineItem Orders Orders_LineItem LineItem id name orders_id item_id id item @Entity @Table(name="Orders") public class Order { @Id private int id; private String name; @OneToMany private Collection<LineItem> lineItems; // Getters and setters go here… } @Entity public class LineItem { @Id private int id; private String item; // Getters and setters go here… } Evntueel bij vertellen dat het ook zonder tussentabel kan in geval van een bidirectionele relatie. In dat geval zal LineItem een veld Order order hebben. In de Order class kan dan op de relatie worden De order colom van LineItem zal dan worden gebruikt om de mapping te realiseren. Gastcollege Fontys – Java Persistence API 4/3/2019
23
Mapping inheritance hierarchy to:
Entities can extend: Other entities Other plain Java classes Mapping inheritance hierarchy to: Single table: everything in one table Requires discriminator value Joined: each class in a separate table Table per concrete class Gastcollege Fontys – Java Persistence API 4/3/2019
24
Example: Inheritance mapping strategies
Pet Single Table id name breed can_fly dsc Pet Bird Dog Joined Tables id name id can_fly id breed Table per concrete class This slide shows three possible mappings for the given code. Single table will be the default mapping. Use annotations to specify which mapping the persistence provider should use. Bird Dog id name can_fly id name breed Gastcollege Fontys – Java Persistence API 4/3/2019
25
EntityManager is a factory for Query objects
Queries EntityManager is a factory for Query objects Using createQuery() methods Uses new and improved EJB-QL Support for static and dynamic queries Queries can be named Queries can return entities, non-entities, or projections of entity data Native queries Not portable across databases! Projections of entity data: select o.item.name, o.quantity from Order o where o.quantity > 100 (levert gedeelte van entity data op) Gastcollege Fontys – Java Persistence API 4/3/2019
26
EJB-QL: Query language for the abstract persistence schema of entities
Vendor and implementation independent Pretty much like SQL, with slightly different syntax SELECT c FROM Customer SELECT c FROM Customer WHERE c.firstName = ‘Bert’ Gastcollege Fontys – Java Persistence API
27
Object[String, String]
Queries by example Bulk updates Group By / Having Projections UPDATE Customer c SET c.firstName = ‘Bert’ Vector Object[String, String] … SELECT e.sex, count(e) FROM Employee e GROUP BY e.sex HAVING e.sex = ‘F’ SELECT e.name, c.name FROM Employee e, Company c WHERE e.company = c Gastcollege Fontys – Java Persistence API
28
Queries by example cont’d
Object creation in SELECT statements Dynamic queries and named params SELECT NEW ejb.CompanyEmployeeInfo(c.name, e.name) FROM Employee e JOIN e.company c @PersistenceContext private EntityManager em; public List findRestaurantsByName(String name) { return em.createQuery("SELECT r FROM Restaurant r " + WHERE r.name LIKE :restName") .setParameter("restName", name).getResultList(); } Gastcollege Fontys – Java Persistence API 4/3/2019
29
Impact on transaction model
Transactions Impact on transaction model Cannot specify transaction attributes on entity itself EJB 3.0 entities always run within transactional context of the caller! Use Session Façade to control transactional behavior! Java EE Best Practice [Blueprints] Gastcollege Fontys – Java Persistence API
30
Set of entities and related classes that share the same configuration
Persistence Unit Set of entities and related classes that share the same configuration Each unit must have unique name Empty string is also considered unique Packaging and deployment unit Standard jar file Contains persistence.xml file in META-INF/ Optionally, contains orm.xml file in META-INF/ Gastcollege Fontys – Java Persistence API
31
Example: persistence.xml
Contains one or more <persistence-unit> elements Each <persistence-unit> element contains (optional) configuration information <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns=" version="1.0"> <persistence-unit name="MyPU" transaction-type="JTA"> <jta-data-source>jdbc/__default</jta-data-source> <properties> <property name="toplink.platform.class.name" value="oracle.toplink.essentials.platform.database.DerbyPlatform"/> <property name="toplink.ddl-generation" value="drop-and-create-tables"/> </properties> </persistence-unit> </persistence> <persistence-unit> Name (required): unique name Transaction-type (optional): JTA (Java EE) or RESOURCE_LOCAL (Java SE) <provider> (optional): fully qualified name of a class that implements the PersistenceProvider interface. <jta-data-source> (optional): global jndi name of datasource to use (if neither is supplied, vendor-provided default will be used) <non-jta-data-source> (optional): global name of datasource to use (if neither is supplied, vendor-provided default will be used) <mapping-file> (optional): The jar file of the persistence unit may optionally contain a mapping XML deployment descriptor in the META-INF directory. Additional mapping files can be referenced using <mapping-file> elements <jar-file> or <class> (optional): a list of jar files or classes belonging to this persistence unit. By default all classes part of the jar file containing the persistence.xml are part of the persistence unit. <exclude-unlisted-classes> (optional): All classes that are not listed do not belong to this persistence unit. Gastcollege Fontys – Java Persistence API 4/3/2019
32
Enterprise JavaBeans 3.0, 5th Edition
Books worth reading Enterprise JavaBeans 3.0, 5th Edition Richard Monson-Haefel, Bill Burke 5th Edition, May 2006 ISBN: X Mastering Enterprise JavaBeans 3.0 Sriganesh, Brose, Silverman 4th Edition, July 2006 ISBN: PDF available as free download Gastcollege Fontys – Java Persistence API 4/3/2019
33
Beginning EJB 3 Application Development
Books worth reading Beginning EJB 3 Application Development Raghu Kodali & Jonathan Wetherbee 1st Edition, September 2006 ISBN: Further reading: My blog: EJB 3.0 spec: JPA faq: faq/persistence.jsp Gastcollege Fontys – Java Persistence API 4/3/2019
34
Gastcollege Fontys – Java Persistence API
35
Q&A Gastcollege Fontys – Java Persistence API
36
Fontys Hogeschool Venlo
Info Support Fontys Hogeschool Venlo Afstuderen bij Info Support Kruisboog 42, 3905 TG, Veenendaal Tel. +31 (0) , Fax +31 (0) 4/3/2019
37
Waarom afstuderen bij Info Support?
Reeds 15 jaar ervaring in het begeleiden van afstudeerders Intensieve begeleiding door afstudeercoördinator, docent en consultant Praktijkgerichte en technische hoogstaande opdrachten Baangarantie en mogelijkheid door te leren Gastcollege Fontys – Java Persistence API
38
Afstudeeropdrachten Afstuderen Verschillende richtingen
-Business Intelligence/ Datawarehouse -Java -.NET -Infra Proof of concept Gebaseerd op de eisen en wensen van de school Gastcollege Fontys – Java Persistence API
39
Profiel afstudeerder Afstuderen
Je bent laatstejaars student aan een IT-gerelateerde opleiding op hbo/wo-niveau Je focus ligt op de technische kant van de informatica Je sociale en communicatieve vaardigheden zijn ook op hbo/wo-niveau Je ziet voor jezelf een mooie carrière in de IT-consultancy Gastcollege Fontys – Java Persistence API
40
Afstudeervoorwaarden
Afstuderen Afstudeervoorwaarden Afstudeervergoeding van € 500,- per maand Opbouw van 2 vakantiedagen per maand Gebruik van een leaseauto Uitgebreid trainingsaanbod binnen ons eigen kenniscentrum Professionele en informele werkomgeving. Gastcollege Fontys – Java Persistence API
41
Uitgangspunten IT Top Traineeship
Afstuderen Uitgangspunten IT Top Traineeship Doelstelling Van IT talent naar (top) IT Specialist, Projectmanager of Lijnmanager Werken en leren Coaching Duur Afstuderen : 6 maanden Opleidingstraject : 6-8 weken Werken en leren : 15 maanden Gastcollege Fontys – Java Persistence API
42
Mail CV met korte motivatie naar recruiter@infosupport.com
Afstuderen Vragen?? Mail CV met korte motivatie naar Gastcollege Fontys – Java Persistence API
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.