JPA development entry instance and jpa entry instance

Source: Internet
Author: User

JPA development entry instance and jpa entry instance

1. What is JPA?

JPA is a Java persistence specification officially proposed by sun. It provides Java developers with an object/relationship ing tool to manage the relational data in Java applications,

It is mainly used to simplify the existing persistent development work and integrate the ORM technology.


The overall idea of JPA is basically the same as that of the existing ORM frameworks such as Hibernate and TopLink. In general, JPA includes the following three technologies:

1. ORM ing metadata (JPA supports two types of metadata: XML and annotation)-Metadata describes the ing between objects and tables.

2. Java persistence API: this API is used to operate entity objects and perform CRUD operations. The framework completes all things for us in the background. developers can free themselves from tedious JDBC and SQL code.

3. query statements: query data through object-oriented rather than database-oriented statements to avoid close coupling between programs and SQL statements.


Ii. JPA instance:

1. code structure:



2. Configure persistence. xml

<?xml version="1.0"?><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="test" transaction-type="RESOURCE_LOCAL">     <provider>org.hibernate.ejb.HibernatePersistence</provider>      <properties>         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>         <property name="hibernate.connection.driver_class" value="org.gjt.mm.mysql.Driver"/>         <property name="hibernate.connection.username" value="root"/>         <property name="hibernate.connection.password" value="root"/>         <property name="hibernate.connection.url"          value="jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=UTF-8"/>         <property name="hibernate.max_fetch_depth" value="3"/>         <property name="hibernate.hbm2ddl.auto" value="update"/>      </properties>   </persistence-unit></persistence>

The JPA specification requires that persistence. xml be placed under the META-INF directory of the class path, and the file name is fixed


3. entity class

(1) Person:

@Entity@Table(name = "person")public class Person {private Integer id;private String name;private Date birthday;private Gender gender = Gender.MAN;private String info;private Byte[] file;private String imagepath;public Person() {}public Person(String name, Date d) {this.name = name;this.birthday = d;}@Id@GeneratedValue(strategy = GenerationType.AUTO)public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}@Column(length = 20, nullable = false, name = "personName")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 Gender getGender() {return gender;}public void setGender(Gender gender) {this.gender = gender;}@Lobpublic String getInfo() {return info;}public void setInfo(String info) {this.info = info;}@Lob@Basic(fetch = FetchType.LAZY)public Byte[] getFile() {return file;}public void setFile(Byte[] file) {this.file = file;}@Transientpublic String getImagepath() {return imagepath;}public void setImagepath(String imagepath) {this.imagepath = imagepath;}}


(2) Gender

public enum Gender {MAN, WOMAN}

4. Test code

Public class PersonTest {private static EntityManager em; private static EntityManagerFactory factory; @ BeforeClasspublic static void before () throws Exception {factory = Persistence. createEntityManagerFactory ("test"); em = factory. createEntityManager () ;}@ AfterClasspublic static void after () throws Exception {em. close (); factory. close () ;}@ Testpublic void save () {em. getTransaction (). begin (); em. persist (n Ew Person ("wangwu", new Date (); em. getTransaction (). commit () ;}@ Testpublic void getPerson1 () {Person person = em. find (Person. class, 1); // get () System. out. println (person. getName () ;}@ Testpublic void getPerson2 () {Person person = em. getReference (Person. class, 2); // load () System. out. println (person. getName () ;}@ Testpublic void updatePerson1 () {em. getTransaction (). begin (); Person person = em. find (Pers On. class, 1); person. setName ("Lao Zhang"); em. getTransaction (). commit () ;}@ Testpublic void updatePerson2 () {em. getTransaction (). begin (); Person person = em. find (Person. class, 1); em. clear (); // Changes the object to a free state person. setName ("Old Wang"); em. merge (person); // used to synchronize updates of objects in the Free State to the database em. getTransaction (). commit () ;}@ Testpublic void delete () {em. getTransaction (). begin (); Person person = em. find (Person. class, 1); em. remove (person ); // The managed entity deletes em. getTransaction (). commit () ;}@ Testpublic void query () {Query query = em. createQuery ("select o from Person o where o. id =? 1 "); query. setParameter (1, 2); Person person = (Person) query. getSingleResult (); System. out. println (person. getName () ;}@ Testpublic void deletequery () {em. getTransaction (). begin (); Query query = em. createQuery ("delete from Person o where o. id =? 1 "); query. setParameter (1, 2); // Delete query.exe cuteUpdate (); em. getTransaction (). commit () ;}@ Testpublic void updatequery () {em. getTransaction (). begin (); Query query = em. createQuery ("update Person o set o. name =: name where o. id =: id "); query. setParameter ("name", "xxx"); query. setParameter ("id", 336620.query.exe cuteUpdate (); em. getTransaction (). commit ();}}

Iii. Summary:

JPA is not a New ORM framework. It is only used to standardize existing ORM technologies. It cannot replace existing ORM frameworks such as Hibernate and TopLink. On the contrary, when using JPA for development, we will still use these ORM frameworks, but the applications developed at this time do not depend on a persistence provider. Applications can run in any JPA environment without modifying the code, truly achieving low coupling and scalable programming.




Entry-level instances for Android Development

We recommend that you take a look at this website. It is very basic and suitable for beginners.
Code.google.com/p/androidbmi/wiki/IntroAndroid

Introduction to JPA

An object Bean consists of an object class and a persistence. xml file. The persistence. xml file is in the Jar file's META-INF directory. The persistence. xml file specifies the default behavior of the data source and EntityManager object used by the Entity Bean. The configuration of the persistence. xml file is described as follows:
<Persistence>
<Persistence-unit name = "xxx">
<Jta-data-source> java:/MySqlDS </jta-data-source>
<Properties>
<Property name = "hibernate. hbm2ddl. auto" value = "create-drop"/>
</Properties>
</Persistence-unit>
</Persistence>
Each persistence-unit node can have one or more persistence content names, data source names, and Hibernate attributes. The name attribute is used to set the persistence name. The jta-data-source node is used as the data source name used by the specified object Bean. When the data source name is specified, the java:/prefix cannot be missing. The data source name is case sensitive. The properties node is used to specify the attributes of Hibernate. If the value of hibernate. hbm2ddl. auto is set to create-drop, the corresponding database table is automatically created and deleted when the entity Bean is released and detached.

Check the configuration of hibernate. hbm2ddl. auto. If yes, Delete this entry.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.