(1), JPA Introduction:
JPA is all called the Java Persistence API, and the Java Persistence API is the Java Persistence interface proposed by Sun Company in the Java EE 5 specification. JPA draws on the strengths of today's Java persistence technology to standardize and simplify the persistence of Java objects. Using JPA persistence objects is not dependent on an ORM framework.
Why use Jap?
Before we say why we need to use JPA, we need to understand why we use ORM technology.
ORM is object-relation-mapping, which is the object relation mapping technology, is the core of object persistence. ORM is the encapsulation of JDBC, which overcomes the various problems of JDBC:
A) cumbersome code issues
With the JDBC API programming access to the database, the code is large, especially when visiting the table with more fields, the code seems cumbersome, cumbersome, easy error. For example: PreparedStatement pstmt=con.preparestatment ("INSERT into account value (?,?,?,?,?,?,?,?,?)");
ORM establishes the relationship between the Java object and the database object, the program ape does not need to write complex SQL statements, directly manipulate the Java object can, thus greatly reducing the amount of code, but also make the program ape more focused on the implementation of business logic.
b) Database object connectivity Issues
Relational data objects, there are various relationships, including 1 to 1, 1 to many, many to 1, many-to-many, cascade and so on. When database objects are updated, with JDBC programming, these relationships must be handled with great care to ensure that there is no error in maintaining these relationships, a process that is very time-consuming and laborious.
ORM establishes the relationship between Java objects and database objects in the same time, it also creates the relationships of Java objects based on the relationship between database objects, and provides a complete and effective mechanism to maintain these relationships.
c) System Architecture issues
JDBC is a data access layer, but when you use JDBC programming, you must know what database the background is in, what tables it has, what fields the tables have, what types of fields are, what is the relationship between the tables, what indexes are created, and the specific information related to the background database.
Using ORM Technology, the database layer can be completely hidden, presented to the program ape only Java objects, the program ape only need to invoke the Java object based on business logic getter and setter method, you can implement the background database operation, the program apes do not have to know what database is used in the background , what tables, what fields, and what are the relationships between tables and tables.
D) Performance issues
With JDBC programming, there are many inefficiencies in the problem.
Pstmt =conn.preparestatement ("INSERT into user_info values (?,?)");
for (int i=0; i<1000; i++) {
Pstmt.setint (1,i);
Pstmt.setstring (2, "User" +i.tostring ());
Pstmt.executeupdate ();
}
The above program will send 1000 SQL statement execution requests to the background database, the execution efficiency is low.
Using ORM Technology, ORM Framework will be based on the detailed database operation needs, will actively delay to send SQL requests to the background database, ORM can also be based on the actual situation, the database access to the operation of the synthesis, to minimize unnecessary database operation requests.
JPA is one of the most popular ORM technologies available today, so he has all the features of ORM technology and, of course, some of his own advantages:
1 standardisation
JPA is one of the Java EE standards published by the JCP organization, so any framework that claims to be compliant with the JPA standard follows the same architecture and provides the same access API, which ensures that JPA-based enterprise applications can be executed in a different JPA framework with little change.
2 support for container-level features
The JPA framework supports container-level transactions such as big data sets, transactions, concurrency, and so on, which makes JPA beyond the limits of a simple persistence framework and plays a greater role in enterprise applications.
3 easy to use, easy to integrate
One of the main goals of JPA is to provide a simpler programming model: creating entities in the JPA framework is as simple as creating Java classes, with no constraints or restrictions whatsoever, but only with Javax.persistence.Entity to gaze at, JPA's framework and interface are also very simple, there are not too many special rules and design patterns of requirements, developers can very easy to grasp. JPA is designed on a non-intrusive basis, so it can be very easy to integrate with other frameworks or containers.
4 query capability comparable to JDBC
JPA's query language is object-oriented rather than database-oriented, and it constructs query statements in object-oriented natural syntax, which can be regarded as the equivalent of Hibernate hql. JPA defines a unique JPQL (Java persistence query Language), JPQL is an extension of EJB QL, a query language for entities that manipulate objects as entities rather than relational database tables, and can support batch updates and changes, JOIN, GROUP by, have, and so on, usually only have SQL to provide advanced query features, and even support subqueries.
5 Support for advanced object-oriented features
JPA can support advanced object-oriented features such as inheritance between classes, polymorphism, and complex relationships between classes, which allows developers to maximize the use of object-oriented models to design enterprise applications without having to handle the persistence of these features in relational databases on their own.
(2), detailed examples
After project project structure is completed, for example:
(Note: The location of the Persistence.xml file determines the root of persistence (persistence root). The root of the persistence is the jar file or the folder that includes the Meta-inf folder (provided that Persistence.xml is located here). This persistence.xml file is generally placed in the Meta-inf under SRC. The name and position are not changed)
A), import the relevant jar package (see) and create the Meta-inf and persistence.xml files.
Persistence.xml configuration such as the following: (I use the data for MySQL, using different database and JPA different implementation version number will result in different configuration content)
<textarea cols= "rows=" "Name=" "Code" class= "xhtml" ><persistence xmlns= "http://java.sun.com/xml/ns/ Persistence "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://java.sun.com/xml/ Ns/persistence http://java.sun.com/xml/ns/persistence/persistence_version=1 "><persistence-unit name=" MYSQLJPA "transaction-type=" resource_local "><properties><property name=" Hibernate.dialect "value=" Org.hibernate.dialect.MySQL5Dialect "/><property name=" Hibernate.connection.driver_class "value=" Com.mysql.jdbc.Driver "/><property name=" Hibernate.connection.username "value=" root "/><property name=" Hibernate.connection.password "value=" 123456 "/><property name=" Hibernate.connection.url "value=" Jdbc:mysql ://localhost:3306/db1 "/><property name=" hibernate.max_fetch_depth "value=" 3 "/><property name=" Hibernate.hbm2ddl.auto "value=" Update "/></properties></persistence-unit></persistence> </textarea>
b), write the entity bean, such as the following:
Package Com.hmk.bean;import Javax.persistence.column;import javax.persistence.entity;import Javax.persistence.generatedvalue;import javax.persistence.Id; @Entitypublic class Person {private int id;private String name; @Id @GeneratedValuepublic int getId () {return Id;} public void setId (int id) {this.id = ID;} @Column (length=12) public String getName () {return name;} public void SetName (String name) {this.name = name;}}
c), write the JUnit test code, such as the following:
Package Junit.test;import Javax.persistence.entitymanager;import Javax.persistence.entitymanagerfactory;import Javax.persistence.persistence;import Org.junit.beforeclass;import Org.junit.test;import Com.hmk.bean.Person; public class Jpatest {@BeforeClasspublic static void Setupbeforeclass () throws Exception {} @Test public void CreateTable () {//Can verify that the generated table is correct entitymanagerfactory factory = Persistence.createentitymanagerfactory ("MYSQLJPA"); Factory.close ();} @Test public void Save () {Entitymanagerfactory factory = persistence.createentitymanagerfactory ("MYSQLJPA"); Entitymanager em = Factory.createentitymanager (); Em.gettransaction (). Begin (); person person = new person (); Person is new state person.setname ("Zhang San"); Em.persist (person); Persistent entity em.gettransaction (). commit (); Em.close (); Factory.close ();} New, managed, de-@test, delete public void update () {Entitymanagerfactory factory = Persistence.createentitymanagerfactory (" MYSQLJPA "); Entitymanager em = Factory.createentitymanager (); Em.gettransaction (). Begin (); Person person = em.find (Person.class, 1);p erson.setname ("HMK"); Person is a managed state em.gettransaction (). commit (); Em.close (); Factory.close ();} @Test public void Update2 () {Entitymanagerfactory factory = persistence.createentitymanagerfactory ("MYSQLJPA"); Entitymanager em = Factory.createentitymanager (); Em.gettransaction (). Begin (); Person person = Em.find (Person.class, 1); Em.clear (); Turns all entities in the entity manager into a de-person.setname ("Hmk2"); Em.merge (person); To change the off-tube status to managed state, the merge can voluntarily choose the Insert or update data em.gettransaction (). commit (); Em.close (); Factory.close ();} @Test public void Remove () {Entitymanagerfactory factory = persistence.createentitymanagerfactory ("MYSQLJPA"); Entitymanager em = Factory.createentitymanager (); Em.gettransaction (). Begin (); Person person = Em.find (Person.class, 1); Em.remove (person); Delete Entity em.gettransaction (). commit (); Em.close (); Factory.close ();} @Test public void Find () {Entitymanagerfactory factory = persistence.createentitymanagerfactory ("MYSQLJPA"); Entitymanager em = Factory.createentitymanager (); PeRson person = Em.find (Person.class, 2); A Get method similar to Hibernate, returns NULLSYSTEM.OUT.PRINTLN (Person.getname ()) When no data is found, Em.close (); Factory.close ();} @Test public void Find2 () {Entitymanagerfactory factory = persistence.createentitymanagerfactory ("MYSQLJPA"); Entitymanager em = Factory.createentitymanager (); Person person = em.getreference (Person.class, 2); Similar to Hibernate's Load method, delayed loading. Exception System.out.println (Person.getname ()) when there is no corresponding data; Find Data Em.close () when actually called; Factory.close ();}}
D), execute the corresponding method in the JUnit test code can be.
JPA Starter sample (with JPA Hibernate implementation version number)