SlideShare a Scribd company logo
1 of 132
Enterprise JavaBean 3.0 & Java Persistence APIs: Simplifying Persistence   Carol McDonald Java Architect Sun Microsystems
Speaker’s Qualifications ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JPA: Simplifying/Unifying/Standardizing Persistence ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Simplifying/Unifying Persistence cont. ,[object Object],[object Object],[object Object],[object Object],[object Object]
Entities ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity Annotated as “Entity” @Id denotes primary key @Entity public class Customer implements Serializable { @Id  protected Long id; protected String name; public Customer() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} … }
Data Model  and O-R Mapping ,[object Object],[object Object],[object Object]
An Example Data Model Maps entity states to data store Maps relationship to other entities Customer int id String name int c_rating Image photo Set<Order> orders Collection<Phone> phones ... Order int id Customer cust ... Phone int id Collection<Customer> custs ... 1 M M N
Simple Mapping Mapping defaults  to matching  column name . Only  configure   if  entity field and table column names are  different   public class Customer {    int id;   String name;    int c_rating;   Image   photo; } @Entity(access=FIELD) @Column(name=“CREDIT”) @Id @Lob CUSTOMER ID NAME CREDIT PHOTO
Entity Annotated as “Entity” @Id denotes primary key @Entity public class Customer implements Serializable { @Id  protected Long id; protected String name; @Transient  protected int reservationCount; public Customer() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} … }
Entity Class for Customer @Entity(access=FIELD)  @Table(name = “customer”) public class Customer { @Id  public int id; ... public String name; @Column(name=”CREDIT”)  public int c_rating; @LOB  public Image photo; ... } Annotated as “Entity” Data are accessed as fields @Id denotes primary key Maps to “customer” table Specify the table column to map to
Relationships
Entity Relationships ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Relationship Mappings – OneToMany Bidirectional   public class Order {   int id; ... Customer   cust ; } public class Customer {   int id;   ... Set<Order> orders; } @Entity(access=FIELD) @Entity(access=FIELD) @ManyToOne @OneToMany(mappedBy=“ cust ”) @Id @Id 1 n has to say  where the foreign key is  using  mappedBy CUSTOMER ID . . . ORDER CUST_ID ID . . .
Example ManyToOne bi-directional Order is the  owner must call  order.setCustomer (cust) whenever order added  to customer.  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Relationship Mappings – ManyToOne Automatically creates a ADDR_ID field for mapping. Can be overridden via @ManyToOne annotation public class  Customer  {  int id;   Address addr ; } CUSTOMER ADDR_ID ID ADDRESS . . . ID @Entity(access=FIELD) @ManyToOne @Id ADDR_ID
Relationship Mappings – ManyToMany public class  Customer  {   int id;   ... Collection<Phone>   phones ; } @Entity(access=FIELD) @Entity(access=FIELD) @Id @Id @ManyToMany @ManyToMany(mappedBy=“phones”) public class  Phone  {   int id; ...   Collection<Customer>   custs ; } Join table name is made up of the 2 entities. Field name is the name of the  entity  plus the name of the  PK  field PHONES _ID CUSTS _ID CUSTOMER ID . . . PHONE ID . . . CUSTOMER_PHONE ID
Relationship Mappings – ManyToMany Can override the default column names PHONES_ID CUST_ID CUSTOMER ID . . . PHONE ID . . . CUST_PHONE @Entity(access=FIELD) public class Customer {   ... @ManyToMany @ JoinTable (table=@Table(name=“CUST_PHONE”), joinColumns =@JoinColumn(name=“CUST_ID”), inverseJoinColumns =@JoinColumn(name=“PHONES_ID”)) Collection<Phone> phones; }
Example ManyToMany bi-directional customer   is the  owning  side:  must add/remove  the phone from the  customer's  phones property. ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Mapping of Embedded Objects @Entity(access=FIELD) @Embedded @Id @Embeddable(access=FIELD) public class  CustomerInfo  {  String name; int credit; @Lob Image   photo; } public class Customer {    int  id ; CustomerInfo info; } Embedded objects  have  no identity of their own . Takes on the identity of the container object CUSTOMER ID NAME CREDIT PHOTO
Entity Inheritance: 3 possibilities: ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity Inheritance – (Abstract) Entity Class @Entity  public   abstract   class  Person { @Id  protected Long id; protected String name; @Embedded  protected Address address; } @Entity  public class  Customer  extends  Person  { @Transient  protected int orderCount; @OneToMany   protected Set<Order> orders = new HashSet(); } @Entity  public class  Employee  extends  Person  { @ManyToOne   protected Department dept; }
Entity Inheritance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity Inheritance – Mapped Superclass @MappedSuperclass  public class  Person { @Id  protected Long id; protected String name; @Embedded  protected Address address; } @Entity  public class  Customer extends Person  { @Transient  protected int orderCount; @OneToMany   protected Set<Order> orders = new HashSet(); } @Entity  public class  Employee extends Person  { @ManyToOne   protected Department dept; }
Entity Inheritance ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity Inheritance – Non Entity Class public class Person { protected String name; } @Entity  public class  Customer extends Person  { //Inherits name but not persisted @Id  public int id; @Transient  protected int orderCount; @OneToMany   protected Set<Order> orders = new HashSet(); } @Entity  public class  Employee extends Person  { //Inherits name but not persisted @Id  public int id; @ManyToOne   protected Department dept; }
Mapping Entity Inheritance to DB Table ,[object Object],[object Object],[object Object],[object Object]
Inheritance mapping strategies Object Model AirAnimal  wingSpan: int LandAnimal  legCount: int Animal  id: int name: String
Inheritance mapping strategies Data Models ,[object Object],each class  is stored in a  separate table each   concrete  class  is stored in a  separate table all classes stored in the  same table ANIMAL ID NAME LAND_ANML ID LEG_COUNT AIR_ANML ID WING_SPAN ,[object Object],[object Object],LAND_ANML ID LEG_COUNT AIR_ANML ID WING_SPAN NAME NAME ANIMAL LEG_CNT ID DISC NAME WING_SPAN
Discriminator Column and Value for Single Table @Entity @Table(name=&quot;ANIMAL&quot;)  @Inheritance(strategy=SINGLE_TABLE) @DiscriminatorColumnName(name=”DISC”) @DiscriminatorValue(“ANIMAL”) public class Animal { @Id protected int id; protected String name; ... } @Entity @DiscriminatorValue(&quot;LANDANIMAL&quot;) public class LandAnimal  extends Animal  { @Column(name=”LEG_CNT”) protected int legCount; ... ANIMAL LEG_CNT ID DISC NAME WING_SPAN
Discriminator Value for SingleTable
Identity ,[object Object],[object Object],[object Object],[object Object],[object Object]
Types of Identity ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],@Id  @GeneratedValue(strategy=SEQUENCE) private int id; @EmbeddedId   private  EmployeePK  pk; @Entity   @IdClass (EmployeePK.class) public class Employee { @Id  private String empName; @Id  private int dept; Class must be @Embeddable
Using orm.xml for Mapping ,[object Object],[object Object],[object Object],[object Object],[object Object]
Example of orm.xml File <entity-mappings> <entity class=”Customer”> <id name=”id”> <generated-value/> </id> <basic name=”c_rating”> <column name=”ratings”/> </basic> ... <one-to-many name=”orders” mapped-by=”cust”/> </entity> ... </entity-mappings> Overriding the default annotations in source
Persistence ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence – Key Concepts ,[object Object],[object Object],[object Object],[object Object]
Persistence Unit Persistence Context Persistence Context Primary interface to interact with underlying persistence engine A set of entities associated with a particular transaction Configuration for entities mapped to a single data store Persistence Unit MyApp Employee e = new Employee(); e.setName(“Lucas”); em.persist(e); persistence.xml
Persistence Unit ,[object Object],[object Object],[object Object],[object Object],< persistence  version=&quot;1.0&quot;  xmlns =&quot; http://java.sun.com/xml/ns/persistence &quot;> < persistence-unit  name=&quot; OrderPU &quot; transaction-type=&quot;JTA&quot;> < provider > org.hibernate.HibernatePersistence </provider> < jta-data-source > jdbc/order </jta-data-source>   < jar-file >../lib/order.jar</jar-file> < class >com.acme.Order</class> </persistence-unit> </persistence> Optional to define entity classes
Persistence – Key Concepts ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
EntityManager Persistence Context Persistence Context Primary interface to interact with underlying persistence engine A set of managed entities associated with a particular transaction Configuration for entities mapped to a single data store Persistence Unit MyApp Employee e = new Employee(); e.setName(“Lucas”); em.persist(e); persistence.xml
Persistence Context and EntityManager ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence Context and EntityManager Persistence  Context EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() SessionBean JavaBean Servlet
Persistence – Key Concepts creates creates Configured by Manages
EntityManager Example @Stateless  public ShoppingCartBean implements ShoppingCart { @PersistenceContext   EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist (orderLine) ; return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) { return ( entityManager.merge ( orderLine ) ); } } Dependency injection
EJB 3.0: Dependency Injection ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity Lifecycle State Diagram ,[object Object],[object Object],[object Object],[object Object],new() ,[object Object],[object Object],[object Object],no longer associated with persistence context New Detached Removed Managed persist() merge () remove () Updates PC ends
Entity Lifecycle Illustrated – The Code @Stateless  public ShoppingCartBean implements ShoppingCart { @PersistenceContext   EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) {   OrderLine newOL= entityManager.merge(orderLine) return ( newOL ) ); } } New entity Managed entity Detached entity
Entity Manager Persist:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cascading Persist example: ManyToOne public class Order {   int id; ... Customer  cust ; } public class Customer {   int id;   ... Set<Order> orders; } @Entity(access=FIELD) @Entity(access=FIELD) @ManyToOne @OneToMany(mappedBy=“cust”) @Id @Id CUSTOMER ID . . . ORDER CUST_ID ID . . .
Persist  OneToMany bi-directional  Not Cascading em.persist to persist the order  @Stateless  public class OrderManagementBean implements OrderManagement { … @PersistenceContext EntityManager em; … public Order  addNewOrder (Long id,Product product){ Customer cust =  em.find (Customer.class,   id);   Order order = new Order(product);   customer.getOrders().add(order); order.setCustomer(cust);   em.persist(order);   return order; } }
Cascading Persist cascade=Persist  Order persisted automatically, when added to Customer @Entity public class Customer { @Id protected Long id; … @OneToMany(cascade=PERSIST) protected Set<Order> orders = new HashSet(); } … public Order addNewOrder(Customer customer, Product product) { Order order = new Order(product); customer.getOrders().add(order); order.setCustomer(cust); return order; }
Entity Manager Find, Remove:  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Remove When order is removed, the lineItems are  removed with it @Entity public class  Order  { @Id protected Long orderId; … @OneToMany(cascade={PERSIST,REMOVE}) protected Set<LineItem>  lineItems  = new HashSet(); } … @PersistenceContext EntityManager em; … public void deleteOrder(Long orderId) { Order order =  em.find(Order.class, orderId); em.remove(order); }
Merge:  ,[object Object],[object Object],[object Object],public Customer storeUpdatedCustomer(Customer cust) { Customer  customer  =entityManager.merge( cust ); return customer; }   Managed Not managed
Merge When order is merged, the  lineItems  are  merged with it @Entity public class Order { @Id protected Long orderId; … @OneToMany(cascade={PERSIST, REMOVE, MERGE}) protected Set<LineItem>  lineItems  = new HashSet(); } … @PersistenceContext EntityManager em; … public Order updateOrder(Order changedOrder) { return em.merge(changedOrder); }
Detached Objects as DTOs ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Returned to caller as  Detached Detached Managed Detached after return
Types of Persistence Context and  Entity Managers Persistence Context Entity Manager Persistence Context Entity Manager Data source same entity
Entity Manager & Persistence Context  Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Container Managed Entity Manager ,[object Object],[object Object],[object Object],[object Object]
Types of Persistence Context ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java™ Transaction Service Application Server Transaction Service Application UserTransaction  interface Resource Manager XAResource   interface Transactional operation TransactionManager Interface Resource EJB Transaction context
Transactions with  Container Managed EntityManager ,[object Object],[object Object],[object Object]
EJB & Container-Managed Entity Manager &  Transaction-scoped Persistence Context @Stateless  public ShoppingCartBean implements ShoppingCart { @PersistenceContext(unitName=”orderPU”)   EntityManager entityManager; public OrderLine  createOrderLine (Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) { return ( entityManager.merge(orderLine) ); } } Persistence context
Spring 2.0  & JPA @Repository @Transactional public class CatalogDAO implements  CatalogService  { @PersistenceContext (unitName=&quot;PetCatalogPu&quot;) private  EntityManager em; public List<Item>  getItems (int firstItem,int batchSize) {    Query q =    em. createQuery(&quot;select object(o) from Item as o&quot;);   q.setMaxResults(batchSize);   q.setFirstResult(firstItem);   List<Item> items= q.getResultList();   return items;  }
Java EE JTA Transactions ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Stateless Session Bean in Java EE 5.0 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],NEW!  Java EE 5 ,[object Object],Container Managed Transaction
Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Session Facade Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence Context  Propagated Transaction Attributes 2. Create Order and   send JMS  message   to Warehouse Application
Persistence Context Propagation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Persistence Context Propagation ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Transaction Example  Application Server Transaction  Manager Transaction context DataBase Server and  JMS Provider Resource Client Controller Inventory Order 1) Check Out TX_REQUIRED TX_REQUIRED BEGIN 4)   Update Inventory 7) createOrder 11) Check context x to see if  updates will work 12) Commit or  rollback Start Prepare 10) END
Web & Container-Managed EM ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Beware of Injected Objects public class ShoppingCartServlet extends HttpServlet { @PersistenceContext EntityManager em ; protected void doPost(HttpServlet req, ...) { Order order order = ...; em.persist(order) ; } public class ShoppingCartServlet extends HttpServlet { @PersistenceUnit (name=&quot; PetstorePu &quot;) protected void doPost(HttpServlet req, ...) { EntityManager em = (EntityManager) new    InitialContext().lookup(&quot;java:comp/env/PetstorePu&quot;); Order order order = ...; em.persist(order); } WRONG CORRECT ,[object Object]
Web and JTA ,[object Object],[object Object],[object Object],[object Object],[object Object]
Web JTA Transaction and Container EM protected void buyBook(String book, int custId, String creditCard) throws … { utx.begin(); Customer customer =    new  CustomerHelper (). getCustomer (custId); Order order =    new  OrderHelper (). create (book, creditCard, customer); utx.commit(); } JTA
Web JTA Transaction and Container EM EM public Order  create (String book, String creditCard, Customer customer) { EntityManager em = (EntityManager)   new InitialContext() .lookup(“java:comp/env/persistence/bookStore”); Order order = new Order(customer); order.setCreditCard(creditCard); order.setBook(book); em.persist (order); } //CustomerHelper public Customer  getCustomer (int id) { EntityManager em = (EntityManager)   new InitialContext().lookup( “ java:comp/env/persistence/bookStore”); return  em.find (Customer.class, id); } // OrderHelper
Recommendation: Stateless Session Beans ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Web component using Stateless Session  ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],No need for Transaction Management
Stateless Session and Container EM No need for JNDI lookup of EM   No need for Transaction Management @Stateless public class OrderMgrBean implements OrderMgr { @PersistenceContext EntityManager em; create(String book, String creditCard, Customer cust) { Order order = new Order(cust); order.setCreditCard(creditCard); order.setBook(book); em.persist(order); } } @Stateless  public class CustomerMgrBean implements CustomerMgr { @PersistenceContext EntityManager em; public Customer getCustomer(int id) { return em.find(Customer.class, id); } }
Types of Persistence Context ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Extended Persistence Context @Stateful  public class ShoppingCart { //Specify that we want an EXTENDED   @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; //Cached order private Order  order ; //Find and cache order public void lookupOrder(String id) { //order remains managed for the lifetime of the bean order  = em.find(Order.class, id); }
Persistence Context- Transactional vs. Extended @Stateless public class OrderSessionStateless implements OrderService { @PersistenceContext(unitName=”java_one”) EntityManager em;  public void  addLineItem (OrderLineItem li){  // First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class OrderSessionStateful implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em;   // Order is a member variable Loaded from the db in lookupOrder   Order order public void  addLineItem (OrderLineItem li){ // No em.find invoked for the order object  order.lineItems.add(li); }
Extended Persistence Context – When?  ,[object Object],[object Object],[object Object],[object Object]
Conversation @Stateful  public class OrderBean { @PersistenceContext(type=EXTENDED) EntityManager em ; public void add(String itemCode, int qty) { ... } public void confirmOrder() { ... } ... } ________________________________________________________________ protected void doPost(HttpServletRequest req, ...) throws ... { String cmd = req.getParameter(“cmd”); if (cmd.equals(“NEW”)) { //Create  stateful  session bean, hold in HttpSession req.getSession().setAttribute(“order”, orderBean); } else if (cmd.equals(“ADD_ITEM”)) { //Add item to order bean orderBean.add(...); } else if (cmd.equals(“CONFIRM”)) { orderBean.confirmOrder(); order.remove(); req.getSession().removeAttribute(“order”); }
Persistence Context Source: Internal benchmarks Does it affect performance? Micro benchmark with lots of lookups
Entity Manager 2 Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Transaction Demarcation ,[object Object],[object Object],[object Object],[object Object],[object Object]
Data Base Transaction Management Transaction Manager EJB Container Resource Manager Data Base JTA A S EJB Local Servlet JDBC  Transactions JTA Transactions servlet Resource Manager EJB servlet servlet servlet Java SE
Application managed Entity Manager and  JTA Transaction ( Web ) @Resource UserTransaction utx; @PersistenceUnit EntityManagerFactory factory; public void createDistributor(String n) { //Begin transaction utx.begin(); EntityManager em  =  emf.createEntityManager() ; //Create entity Distributor dist = new Distributor(); dist.setName(n); //Save it em.persist( dist ) ; //Commit transaction and close EntityManager utx.commit(); em.close() ; }
Application Managed EM Extended Persistence Context Helper public class ExtendedPersistenceContextServlet  extends  HttpServlet  { @PersistenceUnit EntityManagerFactory emf; public EntityManager  getEntityManager (HttpSession s) {   EntityManager em = s.getAttribute(“entityManager”);   if (em==null) {   em = emf.createEntityManager();   s.setAttribute(“entityManager”, em);   }   em.joinTransaction();   return em; } public void  endConversation (HttpSession s) {   getEntityManager().close();   s.removeAttribute(“entityManager”); }
EntityManager in JavaSE ,[object Object],[object Object]
Transaction Demarcation ,[object Object],[object Object],[object Object],[object Object]
Example EntityManager in JavaSE ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
RESOURCE_LOCAL Transaction  Java SE // Create EntityManagerFactory for a persistence unit  // called manager1 EntityManagerFactory emf =  Persistence.createEntityManagerFactory(&quot;manager1&quot;); EntityManager em = emf.createEntityManager(); // Get a transaction instance and start the transaction EntityTransaction tx = em.getTransaction(); // Create a new customer,persist and commit it. tx.begin(); Distributor dist = new Distributor(); dist.setName(&quot;Joe Smith&quot;); em.persist(dist); tx.commit(); em.close(); emf.close();
Summary EntityManager Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Queries ,[object Object],[object Object],[object Object]
Java Persistence Query Language ,[object Object],[object Object],[object Object],[object Object]
Projection ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Subqueries ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Joins ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Queries ,[object Object],[object Object],[object Object],[object Object]
Dynamic Queries public List findWithName (String name) { Query query =  em.createQuery  ( “ SELECT c FROM Customer c” + “ WHERE c.name LIKE  :custName ”) query.setParameter(“ custName ”, name); query.setMaxResults(10); return (query.getResultList()); }
Queries ,[object Object],[object Object],[object Object],[object Object],[object Object]
Static NamedQuery ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Native SQL vs JPQL ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Queries ,[object Object]
Advance Query API ,[object Object],[object Object],Query q = em.createQuery(“select e from Employee e”, Employee.class); //Set cursor to the 6 th  record q. setFirstResult (5); //Retrieve only 100 employess q. setMaxResult (100); Collection<Employee> emps = q.getResultList(); q. setHint (“ toplink.cache-usage ”,  &quot;DoNotCheckCache&quot; );
Stateful Session Scroller @Stateful public class ResultPagerBean implements ResultPager { @PersistenceContext (unitName=&quot;QueryPaging&quot;) private  EntityManager em ; private String reportQueryName; private int  currentPage, maxResults,pageSize ; public void  init (int pageSize, String countQueryName, String reportQueryName) { currentPage = 0; this.pageSize = pageSize; this.reportQueryName = reportQueryName; maxResults  = (Long)  em.createNamedQuery ( countQueryName ) .getSingleResult(); maxResults  = resultCount.longValue(); } public List  getCurrentResults () { return em.createNamedQuery(reportQueryName) . setFirstResult ( currentPage * pageSize ) . setMaxResults ( pageSize ) .getResultList(); } public void next() { currentPage++; }
Polymorphic Queries ,[object Object],[object Object],select avg(e.salary) from  Employee e where e.salary > 80000 This example returns average salaries of all employees, including subtypes of Employee, such as Manager .
Best Practices and Gotchas
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],Locking
Transactions ,[object Object],[object Object]
Executing a Query Outside of a Transaction @Stateless public class QueryServiceBean implements QueryService { @PersistenceContext(unitName=&quot;EmployeeService&quot;) EntityManager em; @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public List  findAllDepartmentsDetached()  { return em.createQuery(&quot;SELECT d FROM Department d&quot;) .getResultList(); } // ... }
Transactions ,[object Object],[object Object],[object Object],EntityManager em = factory.createEntityManager() ; utx.begin() ; em.joinTransaction() ; Join this transaction
Fetch Types ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example Lazy ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Entity benchmark FetchType—Relationship Source: Internal benchmarks
Join Fetch to load relationship ,[object Object],[object Object],[object Object]
Navigating Relationships Options… ,[object Object],[object Object],[object Object],[object Object]
Navigating Relationships ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],The solution
And detached entities… Navigating Relationships ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Parallel Updates to Same Object ,[object Object],[object Object],[object Object],[object Object],No parallel updates expected or detected
How to Guard Against  Parallel Updates? ,[object Object],[object Object],[object Object],[object Object]
Parallel Updates to Same Object ,[object Object],[object Object],[object Object],[object Object],[object Object]
Using Stale Data for Computation ,[object Object],[object Object],[object Object]
[object Object],Using Stale Data for Computation ,[object Object],[object Object]
Optimistic versus Pessimistic Concurrency ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Cascade Type ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],@Entity public class Order { @OneToMany( cascade=PERSIST ,  fetch=LAZY ) Collection<LineItems> lineItems;
Entity merge  Don't @Entity public class Order { @OneToMany(cascade=CascadeType.ALL, ...)  public Collection<OrderLineItem> getLineItems(){ return lineItems; } } @Stateless public class OrderSessionStateless { @PersistenceContext  private EntityManager em; public void applyDiscount( Collection<OrderLineItem> lis){ applyDiscount(lis); em.merge(order); } }
Entity merge  DO @Entity public class Order { @OneToMany(cascade=CascadeType.ALL, ...)  public Collection<OrderLineItem> getLineItems(){ return lineItems; } } @Stateless public class OrderSessionStateless { @PersistenceContext  private EntityManager em; public void applyDiscount( Collection<OrderLineItem> lis){ for(OrderLineItem li : lis) { applyDiscount(li); em.merge(li); } } }
EJB 3.0 Persistence Summary ,[object Object],[object Object],[object Object],[object Object],[object Object]
Enterprise JavaBean 3.0 and Java Persistence APIs: Simplifying Persistence   Carol McDonald [email_address] Sun Microsystems

More Related Content

What's hot

Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpaStaples
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable codeGeshan Manandhar
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An IntroductionNguyen Cao
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring DataOliver Gierke
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
VelocityGraph Introduction
VelocityGraph IntroductionVelocityGraph Introduction
VelocityGraph IntroductionMats Persson
 

What's hot (20)

JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Easy data-with-spring-data-jpa
Easy data-with-spring-data-jpaEasy data-with-spring-data-jpa
Easy data-with-spring-data-jpa
 
Clean code
Clean codeClean code
Clean code
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Solid principles
Solid principlesSolid principles
Solid principles
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Deployment
DeploymentDeployment
Deployment
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
VelocityGraph Introduction
VelocityGraph IntroductionVelocityGraph Introduction
VelocityGraph Introduction
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 

Similar to Java Persistence API

Creating a Facebook Clone - Part XX - Transcript.pdf
Creating a Facebook Clone - Part XX - Transcript.pdfCreating a Facebook Clone - Part XX - Transcript.pdf
Creating a Facebook Clone - Part XX - Transcript.pdfShaiAlmog1
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational MappingRanjan Kumar
 
Advanced c#
Advanced c#Advanced c#
Advanced c#saranuru
 
Java Persistence API 2.0: An Overview
Java Persistence API 2.0: An OverviewJava Persistence API 2.0: An Overview
Java Persistence API 2.0: An OverviewSanjeeb Sahoo
 
Database handling with room
Database handling with roomDatabase handling with room
Database handling with roomSergi Martínez
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate MappingInnovationM
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate MappingInnovationM
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + SpringBryan Hsueh
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpg_hemanth17
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpRaga Vahini
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpSatish Verma
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharpsinghadarsh
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharpMody Farouk
 
Creating a Facebook Clone - Part XIX - Transcript.pdf
Creating a Facebook Clone - Part XIX - Transcript.pdfCreating a Facebook Clone - Part XIX - Transcript.pdf
Creating a Facebook Clone - Part XIX - Transcript.pdfShaiAlmog1
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 

Similar to Java Persistence API (20)

Creating a Facebook Clone - Part XX - Transcript.pdf
Creating a Facebook Clone - Part XX - Transcript.pdfCreating a Facebook Clone - Part XX - Transcript.pdf
Creating a Facebook Clone - Part XX - Transcript.pdf
 
03 Object Relational Mapping
03 Object Relational Mapping03 Object Relational Mapping
03 Object Relational Mapping
 
Advanced c#
Advanced c#Advanced c#
Advanced c#
 
Java Persistence API 2.0: An Overview
Java Persistence API 2.0: An OverviewJava Persistence API 2.0: An Overview
Java Persistence API 2.0: An Overview
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Database handling with room
Database handling with roomDatabase handling with room
Database handling with room
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate Mapping
 
Hibernate Mapping
Hibernate MappingHibernate Mapping
Hibernate Mapping
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
Struts 2 + Spring
Struts 2 + SpringStruts 2 + Spring
Struts 2 + Spring
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to CSharp
Introduction to CSharpIntroduction to CSharp
Introduction to CSharp
 
Creating a Facebook Clone - Part XIX - Transcript.pdf
Creating a Facebook Clone - Part XIX - Transcript.pdfCreating a Facebook Clone - Part XIX - Transcript.pdf
Creating a Facebook Clone - Part XIX - Transcript.pdf
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 

More from Carol McDonald

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUsCarol McDonald
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Carol McDonald
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBCarol McDonald
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...Carol McDonald
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningCarol McDonald
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBCarol McDonald
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Carol McDonald
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Carol McDonald
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareCarol McDonald
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningCarol McDonald
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Carol McDonald
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Carol McDonald
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churnCarol McDonald
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Carol McDonald
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient DataCarol McDonald
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APICarol McDonald
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesCarol McDonald
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataCarol McDonald
 

More from Carol McDonald (20)

Introduction to machine learning with GPUs
Introduction to machine learning with GPUsIntroduction to machine learning with GPUs
Introduction to machine learning with GPUs
 
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
Streaming healthcare Data pipeline using Apache APIs: Kafka and Spark with Ma...
 
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DBAnalyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
Analyzing Flight Delays with Apache Spark, DataFrames, GraphFrames, and MapR-DB
 
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...Analysis of Popular Uber Locations using Apache APIs:  Spark Machine Learning...
Analysis of Popular Uber Locations using Apache APIs: Spark Machine Learning...
 
Predicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine LearningPredicting Flight Delays with Spark Machine Learning
Predicting Flight Delays with Spark Machine Learning
 
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DBStructured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
Structured Streaming Data Pipeline Using Kafka, Spark, and MapR-DB
 
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
Streaming Machine learning Distributed Pipeline for Real-Time Uber Data Using...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real-Ti...
 
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
Applying Machine Learning to IOT: End to End Distributed Pipeline for Real- T...
 
How Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health CareHow Big Data is Reducing Costs and Improving Outcomes in Health Care
How Big Data is Reducing Costs and Improving Outcomes in Health Care
 
Demystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep LearningDemystifying AI, Machine Learning and Deep Learning
Demystifying AI, Machine Learning and Deep Learning
 
Spark graphx
Spark graphxSpark graphx
Spark graphx
 
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
Applying Machine learning to IOT: End to End Distributed Distributed Pipeline...
 
Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures Streaming patterns revolutionary architectures
Streaming patterns revolutionary architectures
 
Spark machine learning predicting customer churn
Spark machine learning predicting customer churnSpark machine learning predicting customer churn
Spark machine learning predicting customer churn
 
Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1Fast Cars, Big Data How Streaming can help Formula 1
Fast Cars, Big Data How Streaming can help Formula 1
 
Applying Machine Learning to Live Patient Data
Applying Machine Learning to  Live Patient DataApplying Machine Learning to  Live Patient Data
Applying Machine Learning to Live Patient Data
 
Streaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka APIStreaming Patterns Revolutionary Architectures with the Kafka API
Streaming Patterns Revolutionary Architectures with the Kafka API
 
Apache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision TreesApache Spark Machine Learning Decision Trees
Apache Spark Machine Learning Decision Trees
 
Advanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming DataAdvanced Threat Detection on Streaming Data
Advanced Threat Detection on Streaming Data
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 

Java Persistence API

  • 1. Enterprise JavaBean 3.0 & Java Persistence APIs: Simplifying Persistence Carol McDonald Java Architect Sun Microsystems
  • 2.
  • 3.
  • 4.
  • 5.
  • 6. Entity Annotated as “Entity” @Id denotes primary key @Entity public class Customer implements Serializable { @Id protected Long id; protected String name; public Customer() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} … }
  • 7.
  • 8. An Example Data Model Maps entity states to data store Maps relationship to other entities Customer int id String name int c_rating Image photo Set<Order> orders Collection<Phone> phones ... Order int id Customer cust ... Phone int id Collection<Customer> custs ... 1 M M N
  • 9. Simple Mapping Mapping defaults to matching column name . Only configure if entity field and table column names are different public class Customer { int id; String name; int c_rating; Image photo; } @Entity(access=FIELD) @Column(name=“CREDIT”) @Id @Lob CUSTOMER ID NAME CREDIT PHOTO
  • 10. Entity Annotated as “Entity” @Id denotes primary key @Entity public class Customer implements Serializable { @Id protected Long id; protected String name; @Transient protected int reservationCount; public Customer() {} public Long getId() {return id;} public String getName() {return name;} public void setName(String name) {this.name = name;} … }
  • 11. Entity Class for Customer @Entity(access=FIELD) @Table(name = “customer”) public class Customer { @Id public int id; ... public String name; @Column(name=”CREDIT”) public int c_rating; @LOB public Image photo; ... } Annotated as “Entity” Data are accessed as fields @Id denotes primary key Maps to “customer” table Specify the table column to map to
  • 13.
  • 14. Relationship Mappings – OneToMany Bidirectional public class Order { int id; ... Customer cust ; } public class Customer { int id; ... Set<Order> orders; } @Entity(access=FIELD) @Entity(access=FIELD) @ManyToOne @OneToMany(mappedBy=“ cust ”) @Id @Id 1 n has to say where the foreign key is using mappedBy CUSTOMER ID . . . ORDER CUST_ID ID . . .
  • 15.
  • 16. Relationship Mappings – ManyToOne Automatically creates a ADDR_ID field for mapping. Can be overridden via @ManyToOne annotation public class Customer { int id; Address addr ; } CUSTOMER ADDR_ID ID ADDRESS . . . ID @Entity(access=FIELD) @ManyToOne @Id ADDR_ID
  • 17. Relationship Mappings – ManyToMany public class Customer { int id; ... Collection<Phone> phones ; } @Entity(access=FIELD) @Entity(access=FIELD) @Id @Id @ManyToMany @ManyToMany(mappedBy=“phones”) public class Phone { int id; ... Collection<Customer> custs ; } Join table name is made up of the 2 entities. Field name is the name of the entity plus the name of the PK field PHONES _ID CUSTS _ID CUSTOMER ID . . . PHONE ID . . . CUSTOMER_PHONE ID
  • 18. Relationship Mappings – ManyToMany Can override the default column names PHONES_ID CUST_ID CUSTOMER ID . . . PHONE ID . . . CUST_PHONE @Entity(access=FIELD) public class Customer { ... @ManyToMany @ JoinTable (table=@Table(name=“CUST_PHONE”), joinColumns =@JoinColumn(name=“CUST_ID”), inverseJoinColumns =@JoinColumn(name=“PHONES_ID”)) Collection<Phone> phones; }
  • 19.
  • 20. Mapping of Embedded Objects @Entity(access=FIELD) @Embedded @Id @Embeddable(access=FIELD) public class CustomerInfo { String name; int credit; @Lob Image photo; } public class Customer { int id ; CustomerInfo info; } Embedded objects have no identity of their own . Takes on the identity of the container object CUSTOMER ID NAME CREDIT PHOTO
  • 21.
  • 22. Entity Inheritance – (Abstract) Entity Class @Entity public abstract class Person { @Id protected Long id; protected String name; @Embedded protected Address address; } @Entity public class Customer extends Person { @Transient protected int orderCount; @OneToMany protected Set<Order> orders = new HashSet(); } @Entity public class Employee extends Person { @ManyToOne protected Department dept; }
  • 23.
  • 24. Entity Inheritance – Mapped Superclass @MappedSuperclass public class Person { @Id protected Long id; protected String name; @Embedded protected Address address; } @Entity public class Customer extends Person { @Transient protected int orderCount; @OneToMany protected Set<Order> orders = new HashSet(); } @Entity public class Employee extends Person { @ManyToOne protected Department dept; }
  • 25.
  • 26. Entity Inheritance – Non Entity Class public class Person { protected String name; } @Entity public class Customer extends Person { //Inherits name but not persisted @Id public int id; @Transient protected int orderCount; @OneToMany protected Set<Order> orders = new HashSet(); } @Entity public class Employee extends Person { //Inherits name but not persisted @Id public int id; @ManyToOne protected Department dept; }
  • 27.
  • 28. Inheritance mapping strategies Object Model AirAnimal wingSpan: int LandAnimal legCount: int Animal id: int name: String
  • 29.
  • 30. Discriminator Column and Value for Single Table @Entity @Table(name=&quot;ANIMAL&quot;) @Inheritance(strategy=SINGLE_TABLE) @DiscriminatorColumnName(name=”DISC”) @DiscriminatorValue(“ANIMAL”) public class Animal { @Id protected int id; protected String name; ... } @Entity @DiscriminatorValue(&quot;LANDANIMAL&quot;) public class LandAnimal extends Animal { @Column(name=”LEG_CNT”) protected int legCount; ... ANIMAL LEG_CNT ID DISC NAME WING_SPAN
  • 31. Discriminator Value for SingleTable
  • 32.
  • 33.
  • 34.
  • 35. Example of orm.xml File <entity-mappings> <entity class=”Customer”> <id name=”id”> <generated-value/> </id> <basic name=”c_rating”> <column name=”ratings”/> </basic> ... <one-to-many name=”orders” mapped-by=”cust”/> </entity> ... </entity-mappings> Overriding the default annotations in source
  • 36.
  • 37.
  • 38. Persistence Unit Persistence Context Persistence Context Primary interface to interact with underlying persistence engine A set of entities associated with a particular transaction Configuration for entities mapped to a single data store Persistence Unit MyApp Employee e = new Employee(); e.setName(“Lucas”); em.persist(e); persistence.xml
  • 39.
  • 40.
  • 41. EntityManager Persistence Context Persistence Context Primary interface to interact with underlying persistence engine A set of managed entities associated with a particular transaction Configuration for entities mapped to a single data store Persistence Unit MyApp Employee e = new Employee(); e.setName(“Lucas”); em.persist(e); persistence.xml
  • 42.
  • 43. Persistence Context and EntityManager Persistence Context EntityManager persist() remove() refresh() merge() find() createQuery() createNamedQuery() contains() flush() SessionBean JavaBean Servlet
  • 44. Persistence – Key Concepts creates creates Configured by Manages
  • 45. EntityManager Example @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist (orderLine) ; return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) { return ( entityManager.merge ( orderLine ) ); } } Dependency injection
  • 46.
  • 47.
  • 48. Entity Lifecycle Illustrated – The Code @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext EntityManager entityManager; public OrderLine createOrderLine(Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) { OrderLine newOL= entityManager.merge(orderLine) return ( newOL ) ); } } New entity Managed entity Detached entity
  • 49.
  • 50. Cascading Persist example: ManyToOne public class Order { int id; ... Customer cust ; } public class Customer { int id; ... Set<Order> orders; } @Entity(access=FIELD) @Entity(access=FIELD) @ManyToOne @OneToMany(mappedBy=“cust”) @Id @Id CUSTOMER ID . . . ORDER CUST_ID ID . . .
  • 51. Persist OneToMany bi-directional Not Cascading em.persist to persist the order @Stateless public class OrderManagementBean implements OrderManagement { … @PersistenceContext EntityManager em; … public Order addNewOrder (Long id,Product product){ Customer cust = em.find (Customer.class, id); Order order = new Order(product); customer.getOrders().add(order); order.setCustomer(cust); em.persist(order); return order; } }
  • 52. Cascading Persist cascade=Persist Order persisted automatically, when added to Customer @Entity public class Customer { @Id protected Long id; … @OneToMany(cascade=PERSIST) protected Set<Order> orders = new HashSet(); } … public Order addNewOrder(Customer customer, Product product) { Order order = new Order(product); customer.getOrders().add(order); order.setCustomer(cust); return order; }
  • 53.
  • 54. Remove When order is removed, the lineItems are removed with it @Entity public class Order { @Id protected Long orderId; … @OneToMany(cascade={PERSIST,REMOVE}) protected Set<LineItem> lineItems = new HashSet(); } … @PersistenceContext EntityManager em; … public void deleteOrder(Long orderId) { Order order = em.find(Order.class, orderId); em.remove(order); }
  • 55.
  • 56. Merge When order is merged, the lineItems are merged with it @Entity public class Order { @Id protected Long orderId; … @OneToMany(cascade={PERSIST, REMOVE, MERGE}) protected Set<LineItem> lineItems = new HashSet(); } … @PersistenceContext EntityManager em; … public Order updateOrder(Order changedOrder) { return em.merge(changedOrder); }
  • 57.
  • 58. Types of Persistence Context and Entity Managers Persistence Context Entity Manager Persistence Context Entity Manager Data source same entity
  • 59.
  • 60.
  • 61.
  • 62. Java™ Transaction Service Application Server Transaction Service Application UserTransaction interface Resource Manager XAResource interface Transactional operation TransactionManager Interface Resource EJB Transaction context
  • 63.
  • 64. EJB & Container-Managed Entity Manager & Transaction-scoped Persistence Context @Stateless public ShoppingCartBean implements ShoppingCart { @PersistenceContext(unitName=”orderPU”) EntityManager entityManager; public OrderLine createOrderLine (Product product , Order order) { OrderLine orderLine = new OrderLine(order, product); entityManager.persist(orderLine); return (orderLine); } public OrderLine updateOrderLine(OrderLine orderLine) { return ( entityManager.merge(orderLine) ); } } Persistence context
  • 65. Spring 2.0 & JPA @Repository @Transactional public class CatalogDAO implements CatalogService { @PersistenceContext (unitName=&quot;PetCatalogPu&quot;) private EntityManager em; public List<Item> getItems (int firstItem,int batchSize) { Query q = em. createQuery(&quot;select object(o) from Item as o&quot;); q.setMaxResults(batchSize); q.setFirstResult(firstItem); List<Item> items= q.getResultList(); return items; }
  • 66.
  • 67.
  • 68. Declarative Transaction Management Example TX_REQUIRED TX_REQUIRED TX_REQUIRED PC PC PC Session Facade Inventory Service Order Service Check Out 1. Update Inventory New Persistence Context Persistence Context Propagated Transaction Attributes 2. Create Order and send JMS message to Warehouse Application
  • 69.
  • 70.
  • 71. Transaction Example Application Server Transaction Manager Transaction context DataBase Server and JMS Provider Resource Client Controller Inventory Order 1) Check Out TX_REQUIRED TX_REQUIRED BEGIN 4) Update Inventory 7) createOrder 11) Check context x to see if updates will work 12) Commit or rollback Start Prepare 10) END
  • 72.
  • 73.
  • 74.
  • 75. Web JTA Transaction and Container EM protected void buyBook(String book, int custId, String creditCard) throws … { utx.begin(); Customer customer = new CustomerHelper (). getCustomer (custId); Order order = new OrderHelper (). create (book, creditCard, customer); utx.commit(); } JTA
  • 76. Web JTA Transaction and Container EM EM public Order create (String book, String creditCard, Customer customer) { EntityManager em = (EntityManager) new InitialContext() .lookup(“java:comp/env/persistence/bookStore”); Order order = new Order(customer); order.setCreditCard(creditCard); order.setBook(book); em.persist (order); } //CustomerHelper public Customer getCustomer (int id) { EntityManager em = (EntityManager) new InitialContext().lookup( “ java:comp/env/persistence/bookStore”); return em.find (Customer.class, id); } // OrderHelper
  • 77.
  • 78.
  • 79. Stateless Session and Container EM No need for JNDI lookup of EM No need for Transaction Management @Stateless public class OrderMgrBean implements OrderMgr { @PersistenceContext EntityManager em; create(String book, String creditCard, Customer cust) { Order order = new Order(cust); order.setCreditCard(creditCard); order.setBook(book); em.persist(order); } } @Stateless public class CustomerMgrBean implements CustomerMgr { @PersistenceContext EntityManager em; public Customer getCustomer(int id) { return em.find(Customer.class, id); } }
  • 80.
  • 81. Extended Persistence Context @Stateful public class ShoppingCart { //Specify that we want an EXTENDED @PersistenceContext (type=PersistenceContextType.EXTENDED) EntityManager em ; //Cached order private Order order ; //Find and cache order public void lookupOrder(String id) { //order remains managed for the lifetime of the bean order = em.find(Order.class, id); }
  • 82. Persistence Context- Transactional vs. Extended @Stateless public class OrderSessionStateless implements OrderService { @PersistenceContext(unitName=”java_one”) EntityManager em; public void addLineItem (OrderLineItem li){ // First, look up the order. Order order = em.find(Order.class, orderID); order.lineItems.add(li); } @Stateful public class OrderSessionStateful implements OrderService { @PersistenceContext(type = PersistenceContextType. EXTENDED )) EntityManager em; // Order is a member variable Loaded from the db in lookupOrder Order order public void addLineItem (OrderLineItem li){ // No em.find invoked for the order object order.lineItems.add(li); }
  • 83.
  • 84. Conversation @Stateful public class OrderBean { @PersistenceContext(type=EXTENDED) EntityManager em ; public void add(String itemCode, int qty) { ... } public void confirmOrder() { ... } ... } ________________________________________________________________ protected void doPost(HttpServletRequest req, ...) throws ... { String cmd = req.getParameter(“cmd”); if (cmd.equals(“NEW”)) { //Create stateful session bean, hold in HttpSession req.getSession().setAttribute(“order”, orderBean); } else if (cmd.equals(“ADD_ITEM”)) { //Add item to order bean orderBean.add(...); } else if (cmd.equals(“CONFIRM”)) { orderBean.confirmOrder(); order.remove(); req.getSession().removeAttribute(“order”); }
  • 85. Persistence Context Source: Internal benchmarks Does it affect performance? Micro benchmark with lots of lookups
  • 86.
  • 87.
  • 88. Data Base Transaction Management Transaction Manager EJB Container Resource Manager Data Base JTA A S EJB Local Servlet JDBC Transactions JTA Transactions servlet Resource Manager EJB servlet servlet servlet Java SE
  • 89. Application managed Entity Manager and JTA Transaction ( Web ) @Resource UserTransaction utx; @PersistenceUnit EntityManagerFactory factory; public void createDistributor(String n) { //Begin transaction utx.begin(); EntityManager em = emf.createEntityManager() ; //Create entity Distributor dist = new Distributor(); dist.setName(n); //Save it em.persist( dist ) ; //Commit transaction and close EntityManager utx.commit(); em.close() ; }
  • 90. Application Managed EM Extended Persistence Context Helper public class ExtendedPersistenceContextServlet extends HttpServlet { @PersistenceUnit EntityManagerFactory emf; public EntityManager getEntityManager (HttpSession s) { EntityManager em = s.getAttribute(“entityManager”); if (em==null) { em = emf.createEntityManager(); s.setAttribute(“entityManager”, em); } em.joinTransaction(); return em; } public void endConversation (HttpSession s) { getEntityManager().close(); s.removeAttribute(“entityManager”); }
  • 91.
  • 92.
  • 93.
  • 94. RESOURCE_LOCAL Transaction Java SE // Create EntityManagerFactory for a persistence unit // called manager1 EntityManagerFactory emf = Persistence.createEntityManagerFactory(&quot;manager1&quot;); EntityManager em = emf.createEntityManager(); // Get a transaction instance and start the transaction EntityTransaction tx = em.getTransaction(); // Create a new customer,persist and commit it. tx.begin(); Distributor dist = new Distributor(); dist.setName(&quot;Joe Smith&quot;); em.persist(dist); tx.commit(); em.close(); emf.close();
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102. Dynamic Queries public List findWithName (String name) { Query query = em.createQuery ( “ SELECT c FROM Customer c” + “ WHERE c.name LIKE :custName ”) query.setParameter(“ custName ”, name); query.setMaxResults(10); return (query.getResultList()); }
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108. Stateful Session Scroller @Stateful public class ResultPagerBean implements ResultPager { @PersistenceContext (unitName=&quot;QueryPaging&quot;) private EntityManager em ; private String reportQueryName; private int currentPage, maxResults,pageSize ; public void init (int pageSize, String countQueryName, String reportQueryName) { currentPage = 0; this.pageSize = pageSize; this.reportQueryName = reportQueryName; maxResults = (Long) em.createNamedQuery ( countQueryName ) .getSingleResult(); maxResults = resultCount.longValue(); } public List getCurrentResults () { return em.createNamedQuery(reportQueryName) . setFirstResult ( currentPage * pageSize ) . setMaxResults ( pageSize ) .getResultList(); } public void next() { currentPage++; }
  • 109.
  • 110. Best Practices and Gotchas
  • 111.
  • 112.
  • 113. Executing a Query Outside of a Transaction @Stateless public class QueryServiceBean implements QueryService { @PersistenceContext(unitName=&quot;EmployeeService&quot;) EntityManager em; @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public List findAllDepartmentsDetached() { return em.createQuery(&quot;SELECT d FROM Department d&quot;) .getResultList(); } // ... }
  • 114.
  • 115.
  • 116.
  • 117. Entity benchmark FetchType—Relationship Source: Internal benchmarks
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129. Entity merge Don't @Entity public class Order { @OneToMany(cascade=CascadeType.ALL, ...) public Collection<OrderLineItem> getLineItems(){ return lineItems; } } @Stateless public class OrderSessionStateless { @PersistenceContext private EntityManager em; public void applyDiscount( Collection<OrderLineItem> lis){ applyDiscount(lis); em.merge(order); } }
  • 130. Entity merge DO @Entity public class Order { @OneToMany(cascade=CascadeType.ALL, ...) public Collection<OrderLineItem> getLineItems(){ return lineItems; } } @Stateless public class OrderSessionStateless { @PersistenceContext private EntityManager em; public void applyDiscount( Collection<OrderLineItem> lis){ for(OrderLineItem li : lis) { applyDiscount(li); em.merge(li); } } }
  • 131.
  • 132. Enterprise JavaBean 3.0 and Java Persistence APIs: Simplifying Persistence Carol McDonald [email_address] Sun Microsystems