Download JPA java persistence

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
JPA java persistence
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.
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.
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
API[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.
Using jpa to persist entities
Some site info
• These sites have some jpql basics (java
persistence query language)
• http://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/apacheopenjpa1.0.2/docs/manual/jpa_langref.html#jpa_langref
_bulk_ops
• http://java.sun.com/developer/technicalArticles/J
2EE/jpa/
Where this example came from
• The openejb examples come with a
JPABean/JPAServlet example and I built
this example by modifying theirs.
Directory structure
• WEB-INF
– Web.xml
– Classes
• META-INF
– Persistence.xml
• Yourpackagename
– Beanclass
– servletclass
Running from a form
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);}
}
}
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 + "]";
}
}
Web.xml – just jpa stuff is needed at bottom with
servlet mapping
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>JPA Servlet Example</display-name>
<servlet>
<servlet-name>JpaServlet</servlet-name>
<servlet-class>mycode.JpaServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>JpaServlet</servlet-name>
<url-pattern>/jpa/*</url-pattern>
</servlet-mapping>
<persistence-unit-ref>
<persistence-unit-ref-name>web.xml/PersistenceUnit</persistence-unit-ref-name>
<persistence-unit-name>my-jpa-example</persistence-unit-name>
</persistence-unit-ref>
<persistence-context-ref>
<persistence-context-ref-name>web.xml/PersistenceContext</persistence-context-ref-name>
<persistence-unit-name>my-jpa-example</persistence-unit-name>
<persistence-context-type>Transactional</persistence-context-type>
</persistence-context-ref>
</web-app>
WEB-INF/classes/METAINF/Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit transaction-type="RESOURCE_LOCAL" name="my-jpaexample">
<jta-data-source>java:openejb/Connector/Default JDBC Database</jta-datasource>
<non-jta-data-source>java:openejb/Connector/Default Unmanaged JDBC
Database</non-jta-data-source>
<class>mycode.JpaBean</class>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings"
value="buildSchema(ForeignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
CRUD with JPA
• Servlet in notes
• I did not complete update for multiple
fields
• Use previous persistence.xml and web.xml
format
Student list
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();
}
CRUD with java persistence:
deleting all the Mary Sues
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();}
add
Added Norman
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();
update
Updating just the year
update
Updating all fields
Updating all fields
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
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