Learn notes JPA

Source: Internet
Author: User

Turn from: http://www.cnblogs.com/holbrook/archive/2012/12/30/2839842.html (think written too good, just stick it in this handy review)

JPA defines the standards for Java ORM and the entity Operations API. This article extracts some of the key information from JPA for review.

If there is a basis for hibernate, this article can also quickly grasp the basic concept of JPA and use.

Table of Contents
    • 1 JPA Overview
    • 2 Entity life cycle
    • 3 Entity Relationship Mapping (ORM)
      • 3.1 Basic Mappings
      • 3.2 ID Generation Policy
      • 3.3 Association relationships
      • 3.4 Inheritance Relations
    • 4 Events and Monitoring
    • 5 Query Language Querying language
      • 5.1 Using Parameters
      • 5.2 Named queries
      • 5.3 Sort
      • 5.4 Aggregate queries
      • 5.5 Updates and deletions
      • 5.6 More
    • 6 Transaction Management
1 JPA Overview

JPA (Java persistence Api,java persistence API), defines the standard interface for object-relational mapping (ORM) and entity object persistence.

JPA is part of the JSR-220 (EJB3.0) specification, which specifies that entity objects (Entitybean) are supported by JPA in JSR-220.

So JPA is not limited to EJB3.0, but as a standard specification for Pojo persistence, it can be run independently from the container, and development and testing is more convenient.

The location of JPA in the app is as follows:

JPA maintains a persistence context, which maintains the life cycle of an entity in the context of persistence. It consists of three main aspects:

    1. ORM Meta data. JPA supports Annotion or XML two forms of describing object-relational mappings.
    2. Entity Operations API. Implements CRUD operations on entity objects.
    3. Query Language. The object-oriented query language JPQL (Java persistence query Language) is contracted.

The main APIs for JPA are defined in the Javax.persistence package. If you are familiar with hibernate, you can easily make a correspondence:

 
org.hibernate javax.persistence Description
Cfg. Configuration Persistence Read configuration information
Sessionfactory Entitymanagerfactory Factory class for creating session/entity Manager
Session Entitymanager Provide entity operations APIs, manage transactions, create queries
Transaction Entitytransaction Management transactions
Query Query Execute Query

2 entity life cycle

The entity life cycle is a very important concept in JPA, describing the state transformations from creation to controlled, from delete to free. The operation of the entity is mainly to change the state of the entity.

The life cycle of entities in JPA is as follows:

    1. New, newly created entity object, no primary key (identity) value
    2. Managed, object in persistence context (persisted), managed by Entitymanager
    3. Detached, the object has been detached from the persistence context, into the application Domain
    4. removed, entity objects are deleted

Entitymanager provides a series of methods to manage the life cycle of entity objects, including:

    1. Persist, the newly created or deleted entity is transformed into a managed state and the data is stored in the database.
    2. Remove, delete the controlled entity
    3. Merge, transform the free entity into a managed state, and the data is stored in the database.

If transaction management is used, the commit/rollback of the transaction also alters the state of the entity.

3 Entity Relationship Mapping (ORM) 3.1 Basic mapping
 
Object End database-Side annotion Optional Annotion
Class Table @Entity @Table (name= "tablename")
Property Column @Column (name = "ColumnName")
Property Primary key @Id @GeneratedValue See ID generation Policy
Property NONE @Transient
3.2 ID generation policy

The ID corresponds to the primary key of the database table and is an important attribute that guarantees uniqueness. JPA provides the following types of ID generation policies

    1. Generatortype.auto, automatically generated by JPA
    2. Generationtype.identity, using the self-growing fields of the database, requires database support (such as SQL Server, MySQL, DB2, Derby, etc.)
    3. Generationtype.sequence, using the database's serial number, requires database support (such as Oracle)
    4. Generationtype.table, the growth of the record ID using the specified database table requires defining a tablegenerator that is referenced in @generatedvalue. For example:

      @TableGenerator (name= "Mygenerator", table= "generatortable", Pkcolumnname = "EntityName", pkcolumnvalue= "myentity", Valuecolumnname = "Pkvalue", allocationsize=1)

      @GeneratedValue (strategy = generationtype.table,generator= "Mygenerator")

3.3 Association relationship

JPA defines 4 relationships of one-to-one, One-to-many, Many-to-one, Many-to-many.

For a database, a foreign key association to another table is usually recorded in one table, and to the entity object, the party holding the associated data is called Owning-side, and the other party is called Inverse-side.

For the convenience of programming, we often want to be able to refer to the Owning-side object in Inverse-side, and then we construct a bidirectional association relationship. In a bidirectional association, you need to define the Mappedby property in Inverse-side to indicate which property is holding the associated data in Owning-side.

The key points to associate relationship mapping are as follows:

 
Relationship Type Owning-side Inverse-side
One-to-one @OneToOne @OneToOne (mappedby= "Othersidename")
One-to-many/many-to-one @ManyToOne @OneToMany (mappedby= "xxx")
Many-to-many @ManyToMany @ManyToMany (mappedby = "xxx")

The owning-side of the many-to-many relationship can use @jointable to declare a custom association table, such as an association table between book and author:

@JoinTable (name = "Bookauthor", Joincolumns = {@JoinColumn (name = "BOOKID", referencedcolumnname = "id")}, Inversejoinco Lumns = {@JoinColumn (name = "Authorid", referencedcolumnname = "id")})

Association relationships can also customize the behavior of deferred loading and cascading operations (Owning-side and Inverse-side can be set separately):

By setting Fetch=fetchtype.lazy or Fetch=fetchtype.eager to determine whether the associated object is lazy-loaded or immediately loaded.

You can set the behavior of a cascade operation by setting Cascade={options}, where options can be a combination of the following:

    • Cascadetype.merge cascading updates
    • Cascadetype.persist Cascade Save
    • Cascadetype.refresh cascading refreshes
    • Cascadetype.remove cascading Deletes
    • Cascadetype.all cascade above 4 types of operations
3.4 Inheritance Relationship

JPA declares an inheritance relationship by adding @inheritance (STRATEGY=INHERITANCETYPE.XXX) to the parent class. A supports 3 kinds of inheritance policies:

    1. Single table Inheritance (inheritancetype.singletable), all classes on the inheritance tree share a table, specify (@DiscriminatorColumn) declarations in the parent class, and specify @discriminatorvalue in each class to differentiate between types.
    2. Class table Inheritance (inheritancetype.joined), a common table of parent-child classes, and the remainder saved to their tables, associated with joins.
    3. Concrete table Inheritance (Inheritancetype.tableperclass), where each concrete class is mapped to its own table.

1 and 2 can support polymorphism, but 1 need to allow multiple join relationships for null,2, 3 is best for relational databases, and not for polymorphic support. The specific application should be based on the need to choose.

4 events and monitoring

These methods can be triggered when an event occurs by labeling @prepersist on the entity's methods, @PostPersist declarations.

5 Query Language querying language

JPA provides two query methods, one based on the primary key query, using the Entitymanager Find method:

T Find (Class entityclass, Object PrimaryKey)

The other is to use the JPQL query language. JPQL are fully object-oriented, with inheritance, polymorphism, and correlation features, similar to Hibernate hql.

Using the Entitymanager CreateQuery method:

Query createquery (String qlstring)

5.1 Using Parameters

You can use parameters in the JPQL statement. JPQL supports both named and positional parameters, but all parameters in one JPQL statement can only use the same type.

Examples are as follows:

    • Command parameters

Query query = em.createquery ("Select p from person p where p.personid=:id"); Query.setparameter ("Id", New Integer (1));

    • Position parameters

Query query = em.createquery ("Select p from person p where p.personid=?1"); Query.setparameter (1,new Integer (1));

5.2 named queries

If a JPQL statement needs to be used in more than one place, you can also use @namedquery or @NamedQueries to predefine a named query on an entity object.

Wherever you need to call, simply reference the name of the query.

For example:

@NamedQuery (name= "Getperson", query= "from person WHERE personid=?1")

@NamedQueries ({@NamedQuery (name= "GetPerson1", query= "from person WHERE personid=?1"), @NamedQuery (name= " Getpersonlist ", query=" from person WHERE age>?1 ")})

Query query = em.createnamedquery ("Getperson");

5.3 Sort

JPQL also supports sorting, similar to the syntax in SQL. For example: Query query = em.createquery ("Select p from person p order by p.age, P.birthday desc");

5.4 aggregation query

The JPQL supports AVG, SUM, COUNT, MAX, Min five aggregate functions. For example:

Query query = em.createquery ("Select Max (p.age) from Person P"); Object result = Query.getsingleresult (); String MaxAge = result.tostring ();

5.5 Update and delete

JPQL is not only used for queries, but also for batch updates and deletions.

Such as:

Query query = em.createquery ("Update Order as O set o.amount=o.amount+10"); Record number of update int result = Query.executeupdate ();

Query query = em.createquery ("Delete from OrderItem item where Item.order in (from order as O where o.amount<100)"); Query.executeupdate ();

query = em.createquery ("Delete from Order as O where o.amount<100"); Query.executeupdate (); Number of records of//delete

5.6 More

Like SQL, JPQL also involves more syntax, which you can refer to: http://docs.oracle.com/cd/E11035_01/kodo41/full/html/ejb3_langref.html

6 Transaction Management

JPA supports local transaction management (resourcelocal) and container transaction management (JTA), and container transaction management can only be used in ejb/web container environments.

The type of transaction management can be configured in the "Transaction-type" element in the Persistence.xml file.

JPA obtains an instance of the transaction (Entitytransaction) through Entitymanager's Gettransaction () method, which can then invoke the transaction's begin (), commit (), rollback () method.

Learn notes JPA

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.