JPA Study Notes-Hello World

Source: Internet
Author: User

Labels: Java applications

650) This. width = 650; "src ="/e/u261/themes/default/images/spacer.gif "alt =" * "style =" font-family: ' ', 'Microsoft yahei'; Border: 1px solid RGB (221,221,221); background-position: 50% 50%; Background-repeat: No-Repeat; "/> JAVA persistence API: APIS for Object Persistence

650) This. width = 650; "src ="/e/u261/themes/default/images/spacer.gif "alt =" * "style =" Background: URL ("/e/u261/lang/ZH-CN/images/localimage.png") No-repeat center; Border: 1px solid # DDD; "/> the Java EE 5.0 standard ORM specification allows applications to access the persistent layer in a unified manner


JPA is an abstraction of hibernate (like the relationship between JDBC and JDBC drivers ):

-JPA is a specification: JPA is essentially an ORM specification, not an ORM framework-Because JPA does not provide ORM implementation, it only develops some specifications and provides some programming API interfaces, however, the specific implementation is provided by the ORM vendor.

-Hibernate is implemented: apart from the ORM framework, Hibernate is also a JPA implementation. In terms of functionality, JPA is a subset of the hibernate function.


One of the goals of JPA is to develop an API that can be implemented by many vendors. Currently, Hibernate 3.2 +, toplink10.1 +, and openjpa both provide JPA implementation.

Hibernate-the initiator of JPA is the author of hibernate-hibernate was compatible with JPA since 3.2

Openjpa-openjpa is an open-source project provided by Apache.

Toplink-toplink was previously charged and is now open-source


Advantages of JPA

Standardization: provides the same API, which ensures that enterprise applications developed based on JPA can run under different JPA frameworks after a few modifications.

Easy to use and 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. You only need to use javax. persistence. entity. The JPA framework and interfaces are also very simple,

Comparable to the query capability of JDBC: the JPA query language is object-oriented, and JPA defines a unique jpql, it also supports batch update and modification, join, group by, having, and other advanced query features that can only be provided by SQL, and even subqueries.

Supports advanced object-oriented features: JPA supports advanced object-oriented features, such as inheritance between classes, polymorphism, and complex relationships between classes, to maximize the use of object-oriented models


JPA includes three technologies

Orm ing metadata: JPA supports two types of metadata: XML and JDK 5.0 annotations. The metadata describes the ing between objects and tables. The framework then persists object to database tables.

JPA APIs: These APIs are used to operate entity objects and perform crud operations. The framework completes all things in the background and developers are freed from tedious JDBC and SQL code.

Query Language (jpql): This is an important aspect in persistent operations. It queries data through object-oriented rather than database-oriented query languages to avoid close coupling between programs and specific SQL statements.


Project directory structure

650) This. width = 650; "src =" http://s3.51cto.com/wyfs02/M01/75/07/wKiom1YwsqXDZ6m4AABmrDrwVLA224.jpg "Title =" qq20151028193330.jpg "alt =" wkiom1ywsqxdz6m4aabmrdrwvla224.jpg "/>


You need to add the hibernate required directory and jar under the JPA directory under Lib, as well as the MySQL driver.

Persistence. xml

<? XML version = "1.0" encoding = "UTF-8"?> <Persistence version = "2.0" 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_2_0.xsd"> <persistence-unit name = "JPA" transaction-type = "resource_local"> <! -- Configure what ORM product to use as JPA Implementation 1. the actual configuration is javx. persistance. SPI. implementation class of persistanceprovider interface 2. if there is only one JPA implementation product in the JPA project, you can also choose not to configure this node --> <provider> Org. hibernate. EJB. hibernatepersistence </provider> <! -- Add a persistence class --> <class> COM. JPA. beans. customer </class> <Properties> <property name = "javax. persistence. JDBC. driver "value =" com. mySQL. JDBC. driver "/> <property name =" javax. persistence. JDBC. URL "value =" JDBC: mysql: // test "/> <property name =" javax. persistence. JDBC. user "value =" root "/> <property name =" javax. persistence. JDBC. password "value =" "/> <! -- Configure the basic attributes of JPA to implement the product, that is, the basic attributes of hibernate --> <property name = "hibernate. format_ SQL "value =" true "/> <property name =" hibernate. show_ SQL "value =" true "/> <property name =" hibernate. hbm2ddl. auto "value =" Update "/> </Properties> </persistence-unit> </persistence>


Customer. Java entity class

@ Table (name = "jpa_customer") @ entitypublic Class Customer {@ column (name = "ID") @ generatedvalue (Strategy = generationtype. auto) @ idprivate integer ID; @ column (name = "last_name") Private string lastname; private string email; private int age; // omit getter stter}


Main. Java

Public class main {public static void main (string [] ARGs) {// 1. create entitymanagerfactorystring persistenceunitname = "JPA"; // persistence. entitymanagerfactory = persistence. createentitymanagerfactory (persistenceunitname); // 2. create entitymanagerentitymanager entitymanager = entitymanagerfactory. createentitymanager (); // 3. enable the transaction entitytransaction = entitymanager. gettransaction (); entitytransaction. begin (); // 3. persistent operation customer = new customer (); customer. setage (22); customer. setemail ("[email protected]"); customer. setlastname ("Shang"); entitymanager. persist (customer); // 5. commit the transaction entitytransaction. commit (); // 6. disable entitymanagerentitymanager. close (); // 7. disable entitymanagerfactoryentitymanagerfactory. close ();}}


JPA basic Annotation

Before the @ entity annotation is used to declare an object class statement, it indicates that the Java class is an object class and maps it to the specified database table. For example, if you declare an object class customer, it maps to the customer table in the database.

@ Table

When the object class is mapped to a different database table name, you need to use the @ table annotation description. This annotation is used in parallel with the @ entity annotation and can be written in a separate statement line before the object class declaration statement, it can also be used with the declaration statement.

@ Table the commonly used option is name, which specifies the table name of the database.

@ Table annotation there are two options catalog and schema used to set the database directory or mode to which the table belongs, usually the database name. The uniqueconstraints option is used to set constraints, which are usually not required.

@ ID annotation is used to declare that the attributes of an object class are mapped to the primary key column of the database. This attribute is usually placed before the attribute declaration statement. It can be the same as the declaration statement or written in a separate row.

@ ID annotation can also be placed before the property's getter method.

@ Generatedvalue is used to mark the generation policy of the primary key, which is specified through the Strategy attribute. By default, JPA automatically selects a primary key generation policy most suitable for the underlying database: sqlserver corresponds to identity and MySQL corresponds to auto increment.

The following policies are defined in javax. Persistence. generationtype:

-Identity: the auto-increment mode of Database ID comes from the primary key field, which is not supported by Oracle;

-Auto: JPA automatically selects the appropriate policy, which is the default option;

-Sequence: generate a primary key through the sequence, and specify the sequence name through @ sequencegenerator annotation. MySQL does not support this method.

-Table: a primary key is generated through a table. The framework uses the table simulation sequence to generate a primary key. This policy makes the application easier to port the database.

@ Basic indicates the ing of a simple attribute to fields in the database table. For the getxxxx () method without any annotation, the default value is @ basic.

Fetch: indicates the read policy for this attribute. There are two types: eager and lazy, which respectively indicate master branch crawling and delayed loading. The default value is eager.

Optional: whether the attribute can be null. The default value is true.

@ Column

When the attribute of an object is different from the column name of the database table mapped to it, the @ column annotation must be used. This attribute is usually placed before the attribute declaration statement of the object and can be used with the @ ID annotation.

The common attribute of @ column annotation is name, which is used to set the name of the column mapped to the database table. The annotation also contains multiple other attributes, such as unique, nullable, and length.

@ Columndefinition attribute marked by column: indicates the actual type of the field in the database. generally, the ORM framework can automatically determine the type of fields in the database based on the attribute type, but the date type still cannot determine whether the field type in the database is date, time or timestamp. in addition, the default ing type of string is varchar. If you want to map the string type to the blob or text field type of a specific database.

@ Column annotation can also be placed before the property's getter Method

@ Transient

This attribute is not a ing of fields to the database table. The ORM framework ignores this attribute.

If an attribute is not a field ing of a database table, you must mark it as @ transient. Otherwise, the ORM framework uses its annotation as @ basic by default.

@ Temporal

The precision of the date type is not defined in the core Java API ). in the database, data of the date type has three precision types: date, time, and timestamp (that is, simply date, time, or both ). you can use the @ temporal annotation to adjust the precision of property ing.

JPA Study Notes-Hello World

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.