Although Hibernate is easy to use, it is still troublesome to compile the ing file. Although the plug-in can be used, later maintenance is still troublesome. The full name of JPA is the Java persistence API, many products that implement this specification, such as Hibernate, are well-known among them. In principle, we should try not to use hibernate. Unfortunately, JPA is only an interface specification, and it is unrealistic to write a set according to the specification, you can only use JPA indirectly through hibernate.
1. The jar package required for hibernate JPA implementation is as follows:
I'm using the hibernate3.6 version, if it is a lower version of hibernate, it also needs hibernate-commons-annotations.jar, hibernate-annotations.jar
2 Persistence. xml configuration
JPA and hibernate need a configuration file similar to hibernate. cfg. xml. This file specifies the relevant database to be operated on. The content is as follows:
<? XML version = "1.0" encoding = "UTF-8"?> <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_1_0.xsd" version = "1.0"> <persistence-unit name = "mypersistunit" transaction-type = "resource_local"> <provider> Org. hibernate. EJB. hibernatepersistence </provider> <Properties> <Property Name = "hibernate. hbm2ddl. Auto" value = "Update"/> <! -- Database Configuration --> <property name = "hibernate. connection. driver_class "value =" com. mySQL. JDBC. driver "/> <property name =" hibernate. connection. URL "value =" JDBC: mysql: // 127.0.0.1: 3306/exercise? Useunicode = true & characterencoding = UTF-8 "/> <property name =" hibernate. connection. username "value =" root "/> <property name =" hibernate. connection. password "value =" 123456 "/> <! -- Specify the Dialect --> <property name = "hibernate. dialect "value =" org. hibernate. dialect. mysql5dialect "/> <property name =" hibernate. show_ SQL "value =" false "/> <property name =" hibernate. format_ SQL "value =" true "/> </Properties> </persistence-unit> </persistence>
I believe that hibernate should be able to understand this configuration file. It should be noted that the name attribute of the persistence-unit node will be used later. In addition, the file name can only be persistence. XML cannot be another name and must be placed under the META-INF folder under SRC, which can be created manually if it does not exist.
3. Compile entity classes
Entity is an important part of JPA. It undertakes the functions of pojo and hibernate-like ing files and is regarded as the core file of JPA. The following is an example.
package org.lxh.info;import java.util.Date;import javax.persistence.Column;import javax.persistence.Embedded;import javax.persistence.Entity;import javax.persistence.EnumType;import javax.persistence.Enumerated;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;import javax.persistence.Temporal;import javax.persistence.TemporalType;@Entity@Table(name = "m_users")public class User {private int id;private String name;private Date birthday;private Sex sex;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}@Column(length=20,nullable=false)public String getName() {return name;}public void setName(String name) {this.name = name;} @Temporal(TemporalType.DATE)public Date getBirthday() {return birthday;}public void setBirthday(Date birthday) {this.birthday = birthday;} @Enumerated(EnumType.STRING) @Column(length=5,nullable=false)public Sex getSex() {return sex;}public void setSex(Sex sex) {this.sex = sex;}}
The Function Description of the annotation is as follows:
@ Entity indicates that this Java class is an object.
@ Table this annotation is used to specify the table corresponding to the object. By default, the table name and object class name are the same.
@ ID: Specifies the primary key.
@ Generatedvalue the annotation configures the primary key generation policy.
@ Column: Specifies the column name, unique constraint, and non-empty constraint of the database table.
@ Temporal is mainly used for date attributes. You can specify the date type.
@ Lob specifies the fields mapped to the database as big text data or byte arrays.
@ Enumerated the specified attribute is enumeration.
4. Compile a simple JPA tool class
package org.lxh.util;import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;public final class JpaUtil { private static EntityManagerFactory em; static{ em=Persistence.createEntityManagerFactory("myPersistUnit"); } public static EntityManager getEntityManager(){ return em.createEntityManager(); }}
5. Basic JPA crud operations
Package Org. lxh. test; import static Org. JUnit. assert. *; import Java. util. *; import javax. persistence. entitymanager; import javax. persistence. entitytransaction; import javax. persistence. query; import org.lxh.info. sex; import org.lxh.info. user; import Org. lxh. util. jpautil; public class test {@ Org. JUnit. testpublic void testinsert () {entitymanager em = NULL; entitytransaction Tx = NULL; try {em = jpautil. getentitymanage R (); Tx = em. gettransaction (); Tx. begin (); User u = new user (); U. setbirthday (new date (); U. setname ("pan baibai"); U. setsex (sex. man); em. persist (U); Tx. commit ();} catch (exception e) {e. printstacktrace ();} finally {If (em! = NULL) {em. close () ;}}@ Org. JUnit. testpublic void testupdate () {entitymanager em = NULL; entitytransaction Tx = NULL; try {em = jpautil. getentitymanager (); Tx = em. gettransaction (); Tx. begin (); User u = new user (); U. setid (2); U. setname ("Jay Chou"); U. setsex (sex. man); U. setbirthday (new date (); em. merge (U); Tx. commit ();} catch (exception e) {e. printstacktrace ();} finally {If (em! = NULL) {em. close () ;}}@ Org. JUnit. testpublic void testdelete () {entitymanager em = NULL; entitytransaction Tx = NULL; try {em = jpautil. getentitymanager (); Tx = em. gettransaction (); Tx. begin (); User u = em. find (user. class, 2); em. remove (U); Tx. commit ();} catch (exception e) {e. printstacktrace ();} finally {If (em! = NULL) {em. close () ;}}/ *** simplest query */@ Org. JUnit. testpublic void testjplquery () {entitymanager em = NULL; entitytransaction Tx = NULL; try {em = jpautil. getentitymanager (); string JPL = "select u from user U"; query q = em. createquery (JPL); List <user> All = Q. getresultlist (); iterator <user> it = All. iterator (); While (it. hasnext () {user = it. next (); system. out. println (user. getname () + "," + User. getbirthday ();} catch (Exception e) {e. printstacktrace ();} finally {If (em! = NULL) {em. close () ;}}/*** update data using named parameters */@ Org. JUnit. testpublic void testjplupdate () {entitymanager em = NULL; entitytransaction Tx = NULL; try {em = jpautil. getentitymanager (); string JPL = "update user U set U. name =: name where u. id =: ID "; query q = em. createquery (JPL); q. setparameter ("name", "Garfield"); q. setparameter ("ID", 33660000q.exe cuteupdate ();} catch (exception e) {e. printstacktrace ();} finally {If (em! = NULL) {em. Close ();}}}}
Finally, we will analyze the disadvantages of JPA:
1> fewer primary key generation policies are provided.
2> NO Cache Mechanism
3> object class annotations and Java code are mixed to reduce readability
I will share with you the one-to-many relationship of JPA tomorrow.
Environment setup and basic CRUD operations for JPA beginners