Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Module 8 The Java Persistence API Java Persistence API 8 Objectives ► Describe the role of the Java Persistence API (JPA) in a Java EE application ► Describe the basics of Object Relational Mapping ► Describe the elements and environment of an entity Component ► Describe the life cycle and operational characteristics of entity components Developing Applications for Java EE Platform 220 Ω Omega Ω 1 Examining Java Persistence 8 ► What is the Java persistence specification? Java Persistence API ► What is data persistence? ► How does the Java Persistence API relate to Java EE application servers? ► What are the key features of the persistence model specified in the Java Persistence API? Developing Applications for Java EE Platform 221 Ω Omega Ω Java Persistence API 8 Static Relationship Mapping - Data Tier Elements Developing Applications for Java EE Platform 222 Ω Omega Ω 2 Java Persistence API 8 Static Relationship Mapping - Object Tier Elements Developing Applications for Java EE Platform 223 Ω Omega Ω Java Persistence API 8 Dynamic Relationship - Object/Data Tier Data Synchronization With entities, the data synchronization is maintained by the persistence provider. Developing Applications for Java EE Platform 224 Ω Omega Ω 3 Java Persistence API 8 The Java Persistence API The Java Persistence API: ► Replaces EJB 2.1 Entity Beans with non-EJB entity classes ► Is a standard API for specifying Object-to-Relational mapping information ► Can be used with or without a Java EE Application Server ─ Container-Managed Persistence ─ Application-Managed Persistence Developing Applications for Java EE Platform 225 Ω Omega Ω Java Persistence API 8 Object Relational Mapping Object Relational Mapping (ORM) software: ► Provides an object-oriented view of the database ► Examples include Oracle’s Toplink and Hibernate Developing Applications for Java EE Platform 226 Ω Omega Ω 4 Java Persistence API 8 Normalized Data Mapping Developing Applications for Java EE Platform 227 Ω Omega Ω Java Persistence API 8 Use of an Entity Component Across a Set of Database Tables Developing Applications for Java EE Platform 228 Ω Omega Ω 5 Java Persistence API 8 Entity Class Requirements Entity classes are coded as standard Java classes with the following requirements: ► javax.persistence.Entity annotation on the class or declared as an Entity in a deployment descriptor ► Must be a public class ► No-argument constructor with public or protected access ► Open to extension, in other word they are not final classes ► Implement Serializable if they are to be returned by remote session beans ► Top-level class, entity classes cannot be inner classes Developing Applications for Java EE Platform 229 Ω Omega Ω Entity Class Example @Entity @Table(name = "TABLE1") public class MyEntity implements Serializable { Java Persistence API 8 import java.io.Serializable; import javax.persistence.*; @Id @Column(name = "ID") private int id; @Column(name = "MSG") private String message; protected MyEntity() { } public MyEntity(int id, String message) { this.id = id; this.message = message; } public int getId() { return id; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } Developing Applications for Java EE Platform 230 Ω Omega Ω 6 Java Persistence API 8 Persistent Fields as Opposed to Persistent Properties Entity classes have their state synchronized with a database. The state of an entity class is obtained from either its variables (fields) or its accessor methods (properties). Fieldbased or property-based access: ► Determined by the placement of annotations ► Cannot have both field-based and property-based access Developing Applications for Java EE Platform 231 Ω Omega Ω Java Persistence API 8 Persistent Fields When using persistent fields, the persistence provider retrieves an object’s state by reading its variables. ► Persistent fields cannot be public ► Should not be read by clients directly ► Unless annotated with @Transient or modified with the transient keyword, all variables are persisted regardless of whether they have a @Column annotation. @Id @Column(name = "ID") private int id; @Column(name = "MSG") private String message; public int getId() { return id; } public String getMessage() { return message; } public void setMessage(String message){ this.message=message; } Developing Applications for Java EE Platform 232 Ω Omega Ω 7 Java Persistence API 8 Persistent Properties When using persistent properties, the persistence provider retrieves an object’s state by calling its accessor methods. ► Methods must be public or protected ► Methods follow the JavaBeans naming convention ► Persistence annotations can only be on getter methods private int id; private String message; @Id @Column(name = "ID") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "MSG") public String getMessage() { return message; } public void setMessage(String message) {this.message=message;} Developing Applications for Java EE Platform 233 Ω Omega Ω Java Persistence API 8 Persistence Data Types Persistence fields or properties can be of the following data types ► Java primitive types ► Java wrappers, such as java.lang.Integer ► java.lang.String ► byte[] and Byte[] ► char[] and Character[] ► Any serializable types including but not limited to: ─ java.util.Date ─ java.sql.Date ─ java.sql.TimeStamp Developing Applications for Java EE Platform 234 Ω Omega Ω 8 Java Persistence API 8 The Concept of a Primary Key ► An entity component distinguishes itself and the data it represents from other entities using a primary key. ► A primary key gives an entity instance its persistent identity. ► They are typically a string or an integer but can also be custom classes that correspond to several database table columns. ► Every entity class must have a primary key. ► Can be auto incrementing. @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID", nullable = false) private int id; Developing Applications for Java EE Platform 235 Ω Omega Ω Java Persistence API 8 Entity Component Primary Key Association Developing Applications for Java EE Platform 236 Ω Omega Ω 9 Java Persistence API 8 Persistence Units A persistence unit is a collection of entity classes stored in a EJB-Jar, WAR, or JAR archive along with a persistence.xml file. A persistence unit: ► Defines what entity classes will be controlled by an entity manager ► Is limited to a single DataSource Developing Applications for Java EE Platform 237 Ω Omega Ω Java Persistence API 8 The persistence.xml file The persistence.xml file: ► Configures which classes make up a persistence unit ► Defines the base of a persistence unit ► Specifies the DataSource used <?xml version="1.0" encoding="UTF-8"?> <persistence version="1.0” xmlns="http://java.sun.com/xml/ns/persistence"> <persistence-unit name="BrokerTool-ejb" transaction-type="JTA"> <jta-data-source>StockMarket</jta-data-source> <jar-file>BrokerLibrary.jar</jar-file> <properties/> </persistence-unit> </persistence> Developing Applications for Java EE Platform 238 Ω Omega Ω 10 Java Persistence API 8 The Persistence Context A persistence context can be thought of as a working copy of a persistence unit. Several persistence contexts using the same persistence unit can be active at the same time. A persistence context: ► Typically lasts the duration of a transaction ► Limits entity instances to a single instance per persistent identity ► Has a management API, known as the entity manager Developing Applications for Java EE Platform 239 Ω Omega Ω Java Persistence API 8 The Entity Manager An Entity Manager provides methods to control events of a persistence context and the life cycle of entity instances in a persistence context. An Entity Manager: ► Provides operations, such as flush(), find(), and createQuery(), to control a persistence context ► Replaces some of the functionality of home interfaces in EJB 2.1 Entity Beans ► Obtained using dependency injection in managed classes. @PersistenceContext private EntityManager em; Developing Applications for Java EE Platform 240 Ω Omega Ω 11 Java Persistence API 8 Entity Instance Management @Remote @Stateless public class BrokerModelImpl implements BrokerModel { @PersistenceContext private EntityManager em; public Stock getStock(String symbol) throws BrokerException{ Stock stock = em.find(Stock.class, symbol); if (stock != null) { return stock; } else { throw new BrokerException("Stock : "+symbol+ " not found"); } } public void addStock(Stock stock) throws BrokerException{ try { em.persist(stock); }catch(EntityExistsException exe) { throw new BrokerException("Duplicate Stock : " + Developing Applications for Java EE Platform 241 Ω Omega Ω stock.getSymbol()); } Java Persistence API 8 } public void updateStock(Stock stock) throws BrokerException { Stock s = em.find(Stock.class, stock.getSymbol()); if (s == null) { throw new BrokerException("Stock : " + stock.getSymbol() " not found"); } else { em.merge(stock); } } public void deleteStock(Stock stock) throws BrokerException { String id = stock.getSymbol(); stock = em.find(Stock.class, id); if (stock == null) throw new BrokerException("Stock : " + stock.getSymbol() +" not found"); else em.remove(stock); } } Developing Applications for Java EE Platform 242 Ω Omega Ω 12 Java Persistence API 8 Entity Instance Life Cycle and Entity Manager Methods Developing Applications for Java EE Platform 243 Ω Omega Ω Java Persistence API 8 Entity Bean States Entity beans have a transitional life cycle. An entity can exist in one of four states: ► New – The entity instance is newly created and not connected to a persistence context. ► Managed – The entity instance is connected to a persistence context and has a unique entity identity. Only one managed instance of a identity can exist in a persistence context. ► Detached – The entity instance is not connected to a persistence context. ► Removed – The entity instance is scheduled for deletion. Developing Applications for Java EE Platform 244 Ω Omega Ω 13 Java Persistence API 8 Entity Manager Methods Developing Applications for Java EE Platform 245 Ω Omega Ω Java Persistence API 8 Entity Life Cycle Callback Annotations An entity instance can be notified before or after life- cycle changes using specially annotated methods in the entity class. Life-cycle annontations: @PrePersist @PostPersist @PreRemove @PostRemove @PreUpdate @PostUpdate @PostLoad Developing Applications for Java EE Platform 246 Ω Omega Ω 14 Java Persistence API 8 Deploying Entity Classes ► To deploy entity classes, you must create a persistence unit. ► A persistence unit includes entity classes and a persistence.xml configuration file. ► The persistence unit exists inside of Java EE modules, such as EJB-JAR files and WAR files. Within these Java EE modules, you can have persistence units that include library jars. Developing Applications for Java EE Platform 247 Ω Omega Ω A persistence unit attempts to include all entity classes in the same EJB module as the persistence.xml file. Java Persistence API 8 Creating a Persistence Unit Using Default Settings Developing Applications for Java EE Platform 248 Ω Omega Ω 15 A persistence unit can be made to include library jar files it would not normally include. Java Persistence API 8 Examining a Persistence Unit Using NonDefault Settings Developing Applications for Java EE Platform 249 Ω Omega Ω Java Persistence API 8 A Native Query Example Native queries are easier to use because they do not require that you learn the Java Persistence query language. However, native queries should not be used extensively because they are non-portable. Query query = em.createNativeQuery("SELECT * FROM Customer", Customer.class); List customers = query.getResultList(); Query query = em.createNativeQuery("SELECT * FROM SHARES WHERE SSN = '" + customerId + "'", CustomerShare.class); List shares = query.getResultList(); Developing Applications for Java EE Platform 250 Ω Omega Ω 16