JPA java persistence - PowerPoint PPT Presentation

1 / 28
About This Presentation
Title:

JPA java persistence

Description:

JPA java persistence Notes from wikipedia Entities A persistence entity is a lightweight Java class that typically represents a table in a relational database. – PowerPoint PPT presentation

Number of Views:357
Avg rating:3.0/5.0
Slides: 29
Provided by: higg2
Category:

less

Transcript and Presenter's Notes

Title: JPA java persistence


1
JPA java persistence
2
Notes from wikipedia
  • Entities
  • A persistence entity is a lightweight Java class
    that typically represents a table in a relational
    database. Entity instances correspond to
    individual rows in the table. Entities typically
    have relationships with other entities, and these
    relationships are expressed through
    object/relational metadata. Object/relational
    metadata can be specified directly in the entity
    class file by using annotations, or in a separate
    XML descriptor file distributed with the
    application.
  • The Java Persistence Query Language
  • The Java Persistence Query Language (JPQL) is
    used to make queries against entities stored in a
    relational database. Queries resemble SQL queries
    in syntax, but operate against entity objects
    rather than directly with database tables.
  • Relationship between Java Persistence API and
    Enterprise JavaBeans
  • The Java Persistence API was defined as part of
    the EJB 3.0 specification, which is itself part
    of the Java EE 5 platform. You do not need an EJB
    container or a Java EE application server in
    order to run applications that use persistence,
    however. Future versions of the Java Persistence
    API will be defined in a separate JSR and
    specification rather than in the EJB
    JSR/specification.
  • The Java Persistence API replaces the persistence
    solution of EJB 2.0 CMP.

3
JPA from wikipedia
  • Relationship between Java Persistence API and
    Java Data Objects API
  • The Java Persistence API was developed in part to
    unify the Java Data Objects API, and the EJB 2.0
    Container Managed Persistence (CMP) API. This
    seems to have been successful as most products
    supporting each of those APIs now support the
    Java Persistence API.
  • The Java Persistence API specifies only
    relational persistence (ORM) for Java (although
    there are providers that support other
    datastores). The Java Data Objects
    specification(s) provides relational persistence
    (ORM), as well as persistence to other types of
    datastores.
  • Relationship between Java Persistence API and
    Service Data Object API
  • The Java Persistence API is designed for
    relational persistence, with many of the key
    areas taken from object-relational mapping tools
    such as Hibernate and TopLink. It is generally
    accepted that the Java Persistence API is a
    significant improvement on the EJB 2.0
    specification. The Service Data Objects (SDO) API
    (JSR 235) has a very different objective to the
    Java Persistence API and is considered
    complementary. The SDO API is designed for
    service-oriented architectures, multiple data
    formats rather than only relational data, and
    multiple programming languages. The Java version
    of the SDO API is managed via the Java Community
    Process and the C version of the SDO API is
    managed via OASIS.

4
More on JPA
  • Motivation for creating Java Persistence API
  • Many enterprise Java developers have been using
    lightweight persistent objects provided by
    open-source frameworks or Data Access Objects
    instead of entity beans because entity beans and
    enterprise beans were considered too heavyweight
    and complicated, and they could only be used in
    Java EE application servers. Many of the features
    of the third-party persistence frameworks were
    incorporated into the Java Persistence API, and
    projects like Hibernate and Open-Source Version
    TopLink Essentials are now implementations of the
    Java Persistence API.
  • Relationship to Hibernate
  • Hibernate is an Open source Object-relational
    mapping framework for Java. Versions 3.2 and
    later provide an implementation for the Java
    Persistence API1.
  • Gavin King is the founder2 of Hibernate. He
    represented JBoss on JSR2203, the JCP expert
    group charged with developing JPA. This led to
    ongoing controversy and speculation centered
    around the relationship between JPA and
    Hibernate. Sun states 4 that ideas were drawn
    from several frameworks including Hibernate and
    JDO.

5
Using jpa to persist entities
6
Some site info
  • These sites have some jpql basics (java
    persistence query language)
  • http//edocs.bea.com/kodo/docs40/full/html/ejb3_ov
    erview_query.html
  • http//www.jpox.org/docs/1_2/jpa/query.html
  • http//openjpa.apache.org/builds/1.0.2/apache-open
    jpa-1.0.2/docs/manual/jpa_langref.htmljpa_langref
    _bulk_ops
  • http//java.sun.com/developer/technicalArticles/J2
    EE/jpa/

7
Where this example came from
  • The openejb examples come with a
    JPABean/JPAServlet example and I built this
    example by modifying theirs.

8
Directory structure
  • WEB-INF
  • Web.xml
  • Classes
  • META-INF
  • Persistence.xml
  • Yourpackagename
  • Beanclass
  • servletclass

9
Running from a form
10
Minimal servlet
  • package mycode
  • import java.util.
  • import javax.persistence.EntityManagerFactory
  • import javax.persistence.PersistenceUnit
  • import javax.persistence.EntityManager
  • import javax.persistence.EntityTransaction
  • import javax.persistence.Query
  • import javax.servlet.ServletException
  • import javax.servlet.ServletOutputStream
  • import javax.servlet.http.HttpServlet
  • import javax.servlet.http.HttpServletRequest
  • import javax.servlet.http.HttpServletResponse
  • import java.io.IOException
  • public class JpaServlet extends HttpServlet
  • _at_PersistenceUnit(name "my-jpa-example")
  • private EntityManagerFactory emf
  • protected void doGet(HttpServletRequest
    request, HttpServletResponse response) throws
    ServletException, IOException
  • response.setContentType("text/plain")
  • ServletOutputStream out
    response.getOutputStream()

11
Minimal bean
  • package mycode
  • import javax.persistence.Entity
  • import javax.persistence.Id
  • import javax.persistence.GeneratedValue
  • import javax.persistence.GenerationType
  • import javax.persistence.Column
  • _at_Entity
  • public class JpaBean
  • _at_Id
  • _at_GeneratedValue(strategy GenerationType.IDEN
    TITY)
  • _at_Column(name "id")
  • private int id
  • _at_Column(name "name")
  • private String name
  • public int getId()

12
Web.xml just jpa stuff is needed at bottom with
servlet mapping
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltweb-app xmlns"http//java.sun.com/xml/ns/javaee"
  • xmlnsxsi"http//www.w3.org/2001/XMLSche
    ma-instance"
  • xsischemaLocation"http//java.sun.com/x
    ml/ns/javaee http//java.sun.com/xml/ns/javaee/web
    -app_2_5.xsd"
  • metadata-complete"false"
  • version"2.5"gt
  • ltdisplay-namegtJPA Servlet Examplelt/display-namegt
  • ltservletgt
  • ltservlet-namegtJpaServletlt/servlet-namegt
  • ltservlet-classgtmycode.JpaServletlt/servlet-clas
    sgt
  • lt/servletgt
  • ltservlet-mappinggt
  • ltservlet-namegtJpaServletlt/servlet-namegt
  • lturl-patterngt/jpa/lt/url-patterngt
  • lt/servlet-mappinggt
  • ltpersistence-unit-refgt
  • ltpersistence-unit-ref-namegtweb.xml/Persistence
    Unitlt/persistence-unit-ref-namegt
  • ltpersistence-unit-namegtmy-jpa-examplelt/persist
    ence-unit-namegt

13
WEB-INF/classes/META-INF/Persistence.xml
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltpersistence xmlns"http//java.sun.com/xml/ns/per
    sistence" version"1.0"gt
  • ltpersistence-unit transaction-type"RESOURCE_LOC
    AL" name"my-jpa-example"gt
  • ltjta-data-sourcegtjavaopenejb/Connector/Defaul
    t JDBC Databaselt/jta-data-sourcegt
  • ltnon-jta-data-sourcegtjavaopenejb/Connector/De
    fault Unmanaged JDBC Databaselt/non-jta-data-source
    gt
  • ltclassgtmycode.JpaBeanlt/classgt
  • ltpropertiesgt
  • ltproperty name"openjpa.jdbc.SynchronizeMapp
    ings" value"buildSchema(ForeignKeystrue)"/gt
  • lt/propertiesgt
  • lt/persistence-unitgt
  • lt/persistencegt

14
CRUD with JPA
  • Servlet in notes
  • I did not complete update for multiple fields
  • Use previous persistence.xml and web.xml format

15
Student list
16
Delete action
  • else if("delete".equals(action)beanname!"")
  • EntityManager em emf.createEntityManager()
  • EntityTransaction transaction
    em.getTransaction()
  • transaction.begin()
  • Query query em.createQuery("delete from JpaBean
    j where j.name name")
  • query.setParameter("name", beanname)
  • int deleted query.executeUpdate()
  • out.println("deleted"deleted)
  • transaction.commit()

17
CRUD with java persistence deleting all the Mary
Sues
18
Add action
  • if (action.equals("add"))
  • out.println("_at_PersistenceUnit" emf)
  • EntityManager em emf.createEntityManager()
  • EntityTransaction transaction
    em.getTransaction()
  • transaction.begin()
  • jpaBean.setName(beanname)
  • jpaBean.setYear(beanyear)
  • jpaBean.setAge(Integer.parseInt(beanage)
    )
  • jpaBean.setGpa(Double.parseDouble(beang
    pa))
  • em.persist(jpaBean)
  • transaction.commit()

19
add
20
Added Norman
21
List action
  • EntityManager em emf.createEntityManager()
  • EntityTransaction transaction
    em.getTransaction()
  • //then list
  • transaction.begin()
  • Query query em.createQuery("SELECT j
    FROM JpaBean j")
  • List beans query.getResultList()
  • for(int i0iltbeans.size()i)
  • jpaBean(JpaBean)beans.get(i)
  • beannamejpaBean.getName()
  • int agejpaBean.getAge()
  • beanyearjpaBean.getName()
  • double gpajpaBean.getGpa()
  • out.println(beanname"\t"age'\t'gp
    a'\t'beanyear)
  • transaction.commit()

22
update
23
Updating just the year
24
update
25
Updating all fields
26
Updating all fields
27
A workaround
  • Couldnt get the prepared statement to work
    except for type strings
  • So I collected results of query and updated them.
    They are persisted.
  • else if("update".equals(action))
  • EntityManager em emf.createEntityManager()
  • EntityTransaction transaction
    em.getTransaction()
  • transaction.begin()
  • Query query em.createQuery("Select j from
    JpaBean as j where j.namename")
  • query.setParameter("name",beanname)
  • List beansquery.getResultList()
  • for(int i0iltbeans.size()i)
  • jpaBean(JpaBean)beans.get(i)
  • double gpaDouble.parseDouble(beangpa)
  • int ageInteger.parseInt(beanage)
  • jpaBean.setAge(age)
  • jpaBean.setYear(beanyear)
  • //for
  • transaction.commit()//update case

28
Params can have names or numbers
  • Query query em.createQuery("Update JpaBean as j
    set j.ageage, j.gpagpa where j.namename")
  • int ageInteger.parseInt(beanage)
  • double gpaDouble.parseDouble(beangpa)
  • query.setParameter("gpa", gpa)
  • query.setParameter(age", age)
  • query.setParameter("name", beanname)
  • int updatedquery.executeUpdate()
  • Or
  • Query query em.createQuery("Update JpaBean as j
    set j.age?1, j.gpa?2 where j.name?3")
  • Then
  • query.setParameter(1, beanname)
  • //etc
  • Note I did not complete the full update at the
    time I made this presentation
Write a Comment
User Comments (0)
About PowerShow.com