topic : jpa kaster nurmukan. overview of jpa entitymanager

29
Topic : JPA Kaster Nurmukan

Upload: victoria-simpson

Post on 02-Jan-2016

266 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

Topic : JPAKaster Nurmukan

Page 2: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Overview of JPA

• EntityManager

Page 3: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• O/R Mapping• Primary entity annotations• EntityManager• Entity Relationships• Practice

Page 4: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

Database TablePOJO

Forward Engineering

Reverse Engineering

Java Persistence API

Page 5: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Java Persistence API (JPA)– Annotations for object-relational mapping

– Data access API

– An object-oriented query language JPQL

• Hibernate– The most popular Java ORM library

– An implementation of JPA

Page 6: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Hibernate without JPA– API: SessionFactory, Session, Query, Transaction

– More features

• Hibernate with JPA– API: EntityManagerFactory, EntityManager, Query, Transaction

– Better portability– Behaviors are better defined and documented

Page 7: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Java classes– Employee.java

• JPA configuration file– persistence.xml

• Code to access the persistent objects– EmployeeTest.java

• (Optional) Logging configuration files– log4j.properties

Page 8: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Plain Java classes (POJOs); however, it is recommended that– Each persistent class has an identity field

– Each persistent class implements the Serializable interface

– Each persistent field has a pair of getter and setter, which don’t have to be public

Page 9: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• @Entity. Mark class as an entity• @Id. Define primary key• @EmbeddedId. Define composite key• @Table(name=“TABLE_NAME”). Define table

name for entity class. • @Column. Define column property.• @Transient. Ignored by persistence framework.• @GeneratedValue,@SequenceGenerator.

Autopopulate column with sequence generator.

Page 10: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• Maintains a cache of instances within a transactional context (persistence context)

• We can acquire EntityManager instance using :Dependency InjectionEntityManagerFactoryJNDI Lookup

• Operations : persist(), merge(), remove(), find(), createNamedQuery(), createQuery()

• Persistence unit is declared in persistence.xml

Page 11: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• @OneToOne. One to One is represented by a single-value entity reference at one or both ends of the relationship

• @OneToMany. This annotation is added to a Collection relationship field.

• @ManyToOne. Indicating that is an entity is part of a Collection

• @ManyToMany. This annotation is assigned to a Collection relationship field to indicate the target entity also has a Collection of the source entity type.

• Lazy vs Eager Binding• Cascade (ALL, PERSIST, MERGE, REMOVE, REFRESH)

Page 12: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 12

javax.persistence.EntityManager• Replaces much of the EJB 2.x “Home”

functionality• Handles O/R Mapping of Entities to the

database• Provides APIs

– inserting objects into database– getting objects from database– synchronizing objects with database– querying database

• Provides caching• Coordinates with transactional services (JTA)• Tightly integrated with Java EE and EJB, but

not limited to that environment

Page 13: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 13

javax.persistence.EntityManager• Replaces much of the EJB 2.x “Home”

functionality• Handles O/R Mapping of Entities to the database• Provides APIs

– inserting objects into database– getting objects from database– synchronizing objects with database– querying database

• Provides caching• Coordinates with transactional services (JTA)

– Tightly integrated with Java EE and EJB, but not limited to that environment

Page 14: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 14

Entities

• (formerly and sometimes still called Entity Beans)

• are now Plain Old Java Objects (POJOs)– nothing special happens when calling new

Author author = new Author();

• are not persistent until associated with an EntityManager

em.persist(author);

Page 15: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 15

Example Author POJO [email protected] class Author { private long id; private long version=0; private String firstName; private String lastName; private String subject; private Date publishDate; public Author() {} public Author(long id) { this.id = id; } @Id @GeneratedValue public long getId() { return id;} private void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } ... }

Warning: Using GeneratedValue without specifying a specific strategy should only be used when you have no intention of controlling how the provider manages primary keys for this object type. This would be rare.

Page 16: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 16

Creating Entity in DatabaseAuthor author = new Author(); //primary key will be genauthor.setFirstName("dr");author.setLastName("seuss");author.setSubject("children");author.setPublishDate(new Date());

log_.info("creating author:" + author);em.persist(author);log_.info("created author:" + author);

//output-creating author:id=0, fn=dr, ln=seuss, subject=children,

pdate=Fri Sep 15 11:54:15 EDT 2006-created author:id=50, fn=dr, ln=seuss, subject=children,

pdate=Fri Sep 15 11:54:15 EDT 2006

Page 17: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 17

Managed and Unmanaged Entities

• Unmanaged state (detached)– instance not associated with an EntityManager– state changes are not tracked– can be serialized to client and returned to be

synchronized with database– nothing equivalent to this state in EJB 2.1 entity beans

• Managed state (attached)– instance associated with an EntityManager– state changes are tracked within a Persistence

Context– EJB 2.1 entity beans were always managed

• client interfaced with data through a proxy or state transferred through a Data Transfer Object

Page 18: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 18

Persistence Context

• A set of attached entity instances managed by an EntityManager

• All entities become detached once closed• Two types

– Transaction-scoped Persistence Contexts• begin/end at transaction boundaries• only made available through container managed

persistence contexts– Extended Persistence Contexts

• live beyond any single transaction• allow longer-lived interactions with database without

lengthy transactions tying up database resources

Page 19: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

19

Persistence Context Examples

• Transaction-scoped (inside server container)@PersistenceContext(unitName=”jpaDemo”)

EntityManager em;@TransactionAttribute(REQUIRED)public void update(long authorId, String type) {

Author author = em.find(Author.class, authorId);author.setType(type);

}

• Extended (inside or outside server container)EntityManager em = Persistence. createEntityManagerFactory(“jpaDemo”).createEntityManager();tx.begin(); //tx 1 beginsAuthor author = em.find(Author.class, authorId);tx.commit(); //tx 1 ends, but author remains managed...tx.begin(); //tx 2 beginsauthor.setType(type);tx.commit(); //tx 2 ends, and author is still managed until close

Page 20: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

20

Persistence Unit

• A set of classes that are mapped to the database

• defined in META-INF/persistence.xml • must have an identity

– “” is a valid identity• Classes

– may be named in persistence.xml file– may be automatically scanned for in the classpath

• orm.xml– optionally provided to augment, provide, or replace

class persistence metadata– (more on orm.xml in Core ORM topic)

Page 21: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 21

Example Component Layout META-INF/ +---persistence.xmlejava + ---examples +---… +---DAOException.class +---AuthorDAO.class +---jpa | +---JPAAuthorDAO.class | +---JPADAOBase.class +--domain +---Author.class

Page 22: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

22

Example persistence.xml<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<persistence-unit name="jpaDemo">

<jta-data-source>java:/ejavaDS</jta-data-source>

<properties> <property name="hibernate.hbm2ddl.auto" value="create"/> <property name="hibernate.show_sql" value="true"/ </properties> </persistence-unit> </persistence>

referenced by name

• global JNDI name by which provider references resource(will be used when deployed within server)• may use properties element in Java SE environments that lack JNDI

• vendor-specific way to configure persistence provider

Page 23: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 23

Another Example persistence.xml<?xml version="1.0" encoding="UTF-8"?><persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">

<persistence-unit name="jpaDemo">

<provider>org.hibernate.ejb.HibernatePersistence</provider>

<properties> <property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.Provider"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.connection.username" value="sa"/> <property name="hibernate.show_sql" value="false"/> <property name="hibernate.hbm2ddl.auto" value="create"/> </properties> </persistence-unit>

</persistence

Page 24: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

24

persistence.xml elements• name – identity to reference Persistence Unit• provider – fully qualified name of javax.persistence.PersistenceProvider

– not needed if provider found in classpath acceptable• mapping-file – resource path to optional mapping file

– can be used to specify <class>es or specify/override @Annotation details• jta-data-source

– vendor-specific reference to data source using JTA transactions• non-jta-data-source

– vendor-specific reference to data source using RESOURCE_LOCAL transactions

• jar-file– optional/additional jar file to scan for classes

• class– specifies entity classes not automatically scanned by provider

• exclude-unlisted-classes– if set, provider will not automatically scan archive for entity classes

• properties– may be used to provide vendor-specific properties to configure persistence

providers

Page 25: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

25

Java SE Steps

• Startup– Get EntityManagerFactory

• Runtime– Create EntityManager– Start Transaction– Interact with Entity Manager– Commit Transaction– Close EntityManager

• Shutdown– Close EntityManagerFactory

Page 26: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

26

updating entities• Updates to managed entities automatically

get propagated to database according to flush policy public Author update(Author author) { Author dbAuthor = em.find(Author.class,author.getId());

dbAuthor.setFirstName(author.getFirstName()); dbAuthor.setLastName(author.getLastName()); dbAuthor.setSubject(author.getSubject()); dbAuthor.setPublishDate(author.getPublishDate()); return dbAuthor;}

– Note that if author passed in was already managed...• the changes have already been queued• the dbAuthor returned from the find() will be the same object as author• the sets are unnecessarily changing the values of the Author to their current

values

Page 27: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

v110912 Java Persistence: EntityManager 27

(optional!)Potential Utiltity Classpackage ejava.examples.dao.jpa;

import java.util.HashMap;import java.util.Map;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;

public class JPAUtil { private static final Map<String, EntityManagerFactory> factories = new HashMap<String, EntityManagerFactory>(); public static EntityManagerFactory getEntityManagerFactory(String puName) { EntityManagerFactory emf = factories.get(puName); if (emf == null) { synchronized(factories) { emf = factories.get(puName); if (emf == null) { emf = Persistence.createEntityManagerFactory(puName); factories.put(puName, emf); } } } return emf; } public static void close() { synchronized(factories) { for(String puName : factories.keySet()) { factories.get(puName).close(); } factories.clear(); } }}

Page 28: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager

• http://www.oracle.com

IndicThreads.com Java Meet June 2006

Page 29: Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager