Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "JPA java persistence. Notes from wikipedia Entities A persistence entity is a lightweight Java class that typically represents a table in a relational."— Presentation transcript:

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. relational databaseannotationsXML 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.SQL 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.EJB 3.0JSR 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.Java Data Objects 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.object-relational mappingHibernateTopLinkService Data Objectsservice-oriented architecturesJava Community ProcessC++

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.Data Access Objectsentity beansHibernateOpen-Source Version TopLink Essentials 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 API[1].HibernateOpen sourceObject-relational mappingJava[1] Gavin King is the founder[2] of Hibernate. He represented JBoss on JSR220[3], 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.Gavin King[2]JBoss[3]JCPSun[4]

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 _overview_query.htmlhttp://edocs.bea.com/kodo/docs40/full/html/ejb3 _overview_query.html http://www.jpox.org/docs/1_2/jpa/query.html http://openjpa.apache.org/builds/1.0.2/apache- openjpa- 1.0.2/docs/manual/jpa_langref.html#jpa_langref _bulk_opshttp://openjpa.apache.org/builds/1.0.2/apache- openjpa- 1.0.2/docs/manual/jpa_langref.html#jpa_langref _bulk_ops http://java.sun.com/developer/technicalArticles/J 2EE/jpa/http://java.sun.com/developer/technicalArticles/J 2EE/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 { @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(); String beanname = request.getParameter("name"); out.println("@PersistenceUnit=" + emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); JpaBean jpaBean = new JpaBean(); jpaBean.setName(beanname); em.persist(jpaBean); transaction.commit(); transaction.begin(); Query query = em.createQuery("SELECT j FROM JpaBean j"); List beans = query.getResultList(); for(int i=0;i<beans.size();i++){ beanname=((JpaBean)beans.get(i)).toString(); out.println(beanname);} }

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; @Entity public class JpaBean { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name = "name") private String name; public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "[ id=" + id + ", name=" + name + "]"; }

12 Web.xml – just jpa stuff is needed at bottom with servlet mapping <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" metadata-complete="false" version="2.5"> JPA Servlet Example JpaServlet mycode.JpaServlet JpaServlet /jpa/* web.xml/PersistenceUnit my-jpa-example web.xml/PersistenceContext my-jpa-example Transactional

13 WEB-INF/classes/META- INF/Persistence.xml java:openejb/Connector/Default JDBC Database java:openejb/Connector/Default Unmanaged JDBC Database mycode.JpaBean

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("@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(beangpa)); 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 i=0;i<beans.size();i++){ jpaBean=(JpaBean)beans.get(i); beanname=jpaBean.getName(); int age=jpaBean.getAge(); beanyear=jpaBean.getName(); double gpa=jpaBean.getGpa(); out.println(beanname+"\t"+age+'\t'+gpa+'\t'+beanyear);} transaction.commit();

22 update

23 Updating just the year

24 update

25 Updating all fields

26

27 A “workaround” Couldn’t 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.name=:name"); query.setParameter("name",beanname); List beans=query.getResultList(); for(int i=0;i<beans.size();i++){ jpaBean=(JpaBean)beans.get(i); double gpa=Double.parseDouble(beangpa); int age=Integer.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.age=:age, j.gpa:gpa where j.name=:name"); int age=Integer.parseInt(beanage); double gpa=Double.parseDouble(beangpa); query.setParameter("gpa", gpa); query.setParameter(“age", age); query.setParameter("name", beanname); int updated=query.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


Download ppt "JPA java persistence. Notes from wikipedia Entities A persistence entity is a lightweight Java class that typically represents a table in a relational."

Similar presentations


Ads by Google