Click here to load reader

Ecom lec4 fall16_jpa

  • View

  • Download

Embed Size (px)

Text of Ecom lec4 fall16_jpa

E-commerce SystemsInstructor: Dr. Zainab KhalloufJava Persistence APIAcknowledgementsLecture notes adapted from: [1]. The Java EE 7 Tutorial.[2]. Enterprise JavaBeans 3.1, sixth edition, by Andrew Lee Rubinger, Bill Burke, O'Reilly Media, released: September 2010.[3].[4].

:A Java EE application server contains three essential containers: Web container, EJBs container, and persistence provider.

Figure from: to the Java Persistence API Java Persistence API (JPA) ( Entity) (object relational mapping (ORM)) (persistence provider) : EclipseLink Oracle TopLink Hibernate...

An entity class represents a table in a relational database, and each entity instance corresponds to a row in that table. In the entity, all fields not annotated javax.persistence.Transient or not marked as transient will be persisted to the data store.Example:public class EntityWithTransientFields {transient int transient3; // not persistent because of [email protected] int transient4; // not persistent because of @Transient}

Requirements for Entity ClassesAn entity class must follow these requirements: The class must be annotated with the javax.persistence.Entity (@Entity) annotation. The class must have a public or protected, no-argument constructor. The class may have other constructors. The class must not be declared final. No methods or persistent instance variables must be declared final. If an entity instance is passed by value, such as through a session bean's remote business interface, the class must implement the Serializable interface. Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. Persistent instance variables must be declared private, or protected and can be accessed directly only by the entity classs methods. Clients must access the entitys state through getter/setter or business methods. Each entity has a unique object identifier. (A customer entity, for example, might be identified by a customer number). The unique identifier, or primary key, enables clients to locate a particular entity instance. Managing Entities Entities are managed by the entity manager, which is represented by javax.persistence.EntityManager instance. The EntityManager API creates and removes persistent entity instances, finds entities by the entity's primary key, and allows queries to be run on entities. An EntityManager maps a fixed set of classes to a particular database. This set of classes is called a persistence unit. A persistence unit is defined in a persistence.xml file. This file is a required deployment descriptor for the Java Persistence specification. Example:

There are two types of Entity Managers:1. Container-Managed EntityManagers: An EntityManager can be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation. Example:

2. Application-Managed EntityManagers:( ) The EntityManager and its associated persistence context are created and destroyed explicitly by the application. To obtain an EntityManager instance, you first must obtain an EntityManagerFactory instance by injecting it into the application component by means of the javax.persistence.PersistenceUnit annotation: @PersistenceUnit EntityManagerFactory emf; Then obtain an EntityManager from the EntityManagerFactory instance: EntityManager em = emf.createEntityManager();

In this case, the application needs to access the JTA transaction manager and add transaction information when performing entity operations. The javax.transaction.UserTransaction interface defines methods to begin, commit, and roll back transactions. Inject an instance of UserTransaction by creating an instance variable annotated with @Resource:

@ResourceUserTransaction utx; The following example shows how to manage transactions in an application that uses an application-managed entity manager:@PersistenceUnitEntityManagerFactory emf;EntityManager em;@ResourceUserTransaction utx;...em = emf.createEntityManager();try {utx.begin();em.persist(SomeEntity);em.merge(AnotherEntity);em.remove(ThirdEntity);utx.commit();} catch (Exception e) {utx.rollback();}Persisting Entity Instances New entity instances become managed and persistent either by invoking the persist method. The entity's data is stored to the database when the transaction associated with the persist operation is completed.Synchronizing Entity Data to the Database To force synchronization of the managed entity to the data store, invoke the flush method of the EntityManager instance. If the entity is removed, calling flush will remove the entity data from the data store.Entity Example In NetBeans (Code First Approach): Let's write a JEE 7 application which contains an entity class and session facade, then writing a standalone client.

Step 1:

Step 2:

Step 3:

"create-tables" - will only attempt to create tables, if the table already exists then it will not be dropped or replaced, the existing table will be used. "drop-and-create-tables" - will first drop the existing table, and then create the new table.


1 package entities; 2 3 import; 4 import javax.persistence.Entity; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.GenerationType; 7 import javax.persistence.Id; 8 9 10 @Entity11 public class Account implements Serializable {12 13 private static final long serialVersionUID = 1L;14 @Id15 @GeneratedValue(strategy = GenerationType.AUTO)16 private Long id;17 private String ownerName;18 private int balance;19 20 public Account() {21 //id = (Long) System.nanoTime();22 }23 24 public int getBalance() {25 return balance;26 }27 28 public void setBalance(int balance) {29 this.balance = balance;30 }31 32 public String getOwnerName() {33 return ownerName;34 }35 36 public void setOwnerName(String ownerName) {37 this.ownerName = ownerName;38 }39 40 public Long getId() {41 return id;42 }43 44 public void setId(Long id) {45 = id;46 }47 48 public void deposit(int amount) {49 balance += amount;50 }51 52 public int withdraw(int amount) {53 if (amount > balance) {54 return 0;55 } else {56 balance -= amount;57 return amount;58 }59 }60 61 @Override62 public int hashCode() {63 int hash = 0;64 hash += (id != null ? id.hashCode() : 0);65 return hash;66 }67 68 @Override69 public boolean equals(Object object) {70 // TODO: Warning - this method won't work in the case the id fields are not set71 if (!(object instanceof Account)) {72 return false;73 }74 Account other = (Account) object;75 if (( == null && != null) || ( != null && ! {76 return false;77 }78 return true;79 }80 81 @Override82 public String toString() {83 return "entities.Account[ id=" + id + " ]";84 }85 86 }87

Step 5:

1 package session; 2 3 import entities.Account; 4 import java.util.List; 5 import javax.ejb.Remote; 6 import javax.persistence.Query; 7 @Remote 8 public interface AccountFacadeInterface { 9 10 public Account openAccount(String ownerName, int balance);11 12 public void deposit(int accountNumber, int amount);13 14 public int withdraw(int accountNumber, int amount);15 16 public void close(int accountNumber);17 18 public List listAccounts();19 }20

1 package session; 2 import entities.Account; 3 import; 4 import java.util.List; 5 import javax.ejb.Stateless; 6 import javax.ejb.LocalBean; 7 import javax.persistence.EntityManager; 8 import javax.persistence.PersistenceContext; 9 import javax.persistence.Query;10 11 @Stateless12 public class AccountFacade implements AccountFacadeInterface{13 14 @PersistenceContext(unitName = "AccountEntitySample-ejbPU")15 private EntityManager em;16 17 public Account openAccount(String ownerName, int balance) {18 Account account = new Account();19 account.setOwnerName(ownerName);20 account.setBalance(balance);21 em.persist(account);22 return account;23 }24 25 public void deposit(int accountNumber, int amount) {26 Account account = em.find(Account.class, accountNumber);27 account.deposit(amount);28 }29 30 public int withdraw(int accountNumber, int amount) {31 Account account = em.find(Account.class, accountNumber);32 return account.withdraw(amount);33 }34 35 public void close(int accountNumber) {36 Account account = em.find(Account.class, accountNumber);37 em.remove(account);38 }39 40 public List listAccounts() {41 Query query = em.createQuery("SELECT a FROM Account a");42 return query.getResultList();43 }44 }45

Step 6:

Now we can see the generated Account table.

Step 7:The standalone client.

Entity Example In NetBeans (Database First Approach): -Generating Entities from a database, then generating the facade session beans. This approach is illustrated in the following snapshots:

Primary Keys in Entities Every entity must have a primary key. An entity may have either a simple or a composite primary key.Simple primary keys Use the javax.persistence.Id (@Id) annotation to denote the