1.JPA Introduction:
The Java Persistence specification, which is separated from the previous entity bean (Entity bean) of ejb2.x, EJB3 no more entity beans at a later time, but instead the entity Bean is implemented in JPA. JPA is a Sun proposed object persistence specification, each Java EE application Server chooses the specific implementation, the JPA Designer is the hibernate framework author, therefore hibernate as the JPA server in the default implementation, Oracle's WebLogic uses Eclipselink (formerly known as TopLink) as the default JPA implementation, and IBM's WebSphere and Sun GlassFish default to use OPENJPA (an open source project from Apache) As its default JPA implementation.
The underlying implementation of JPA is a popular open source ORM (Object Relational Mapping) framework, so JPA is actually a mapping relationship between Java entity objects and relational databases, and the specification of relational databases is manipulated through object-oriented programming ideas.
2.JPA Persistence policy File:
In Entity bean applications, as required by the JPA specification, the persistent profile--persistence.xml is required to be added to the Meta-inf directory of the Application Classpath (CLASSPATH), which is the persistent policy file. Its contents are as follows:
[XHTML] View plain Copy
<?xml version= "1.0" encoding= "UTF-8"?> <persistence version= "1.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_1_0.xsd ">
<persistence-unit name=" Persistent cell name "transaction-type=" JTA >
<jta-data-source> The data source deployed on the Java EE server using JCA jndi</jta-data-source >
<. --Specify the JPA implementation provider, without specifying the default JPA provider for the Java EE server, taking OPENJPA as an example-->
<provider> org.apache.openjpa.persistence.persistenceproviderimpl</provider>
<class> Entity bean full path name </class > ...
<properties>
<!--Configure some of the JPA implementation provider's information-->
</properties>
</persistence-unit>
</persistence>
Note: Multiple persistence unit Persistence-unit can be configured in the persistence policy file, and multiple persistence units are often configured when using distributed databases.
3. Development of Entity Beans:
Basic specification for Entity bean Development defined in the JPA specification:
(1). Add a "@Entity" annotation on the entity bean to identify the bean as an entity bean.
(2). Entity beans must be serialized.
(3). Use the @Table (name= database table name) annotation to identify the name of the table that the entity bean maps to in a relational database, and the JPA implementation automatically generates the default table name if not specified.
(4). You must have a primary key that is identified by using the "@Id" annotation, such as specifying a self-added primary key as:
[Java] View plain copy
@Id
@Column (name= "column name")
@GeneratedValue (strategy=generationtype.auto)
private int Id;
Note: The @Id and @generatedvalue two annotations must be used at the same time, after the annotation has been identified, to generate a policy for the primary key.
(5). Other properties of the bean use the @Column (name= column name) annotation to specify that the property is mapped to a column name in a database table, and if not specified, the default column name is automatically generated in the JPA implementation.
(6). Entity beans must adhere strictly to the JavaBean specification, provide a default constructor without parameters, and properties that provide set and get methods.
(7). It is best to rewrite the hashcode () and Equals () methods, and the entity Bean's unique identity is the primary key, so the entity Bean's primary key is used for comparison.
4. Entity Bean's primary key generation policy:
The annotation generation policy for entity beans uses the "@GeneratedValue" annotation to specify a primary key generation policy, by default the auto self increase policy, JPA does not support Hibernate's UUID primary key generation policy, to use the Hibernate UUID key method, The method is as follows:
(1). Add the Hibernate.annotation jar package to the classpath.
(2) Add the following annotation at the same time on the field using "@Id":
[Java] View plain copy
@GeneratedValue (generator= "UUID primary key Generation policy")
@GenericGenerator (name= "UUID primary key Generation policy", strategy= "UUID")
5.JPA Development Considerations:
JPA supports XML and annotation methods, and as annotations are becoming more mature and popular, the most common way to develop JPA is to use annotations only, so it has to be in the JavaEE5 version, because the previous version has no support for annotations.
The advantages and disadvantages of Java annotations compared to XML files:
Advantage:
(1). The descriptor is reduced and the development efficiency is greatly improved.
(2). Compile-time checksum, error annotations will be incorrect during compilation.
(3). Annotations are in Java code, thereby avoiding additional file maintenance work.
(4). Annotations are compiled into Java bytecode, consume less memory, read faster, and often parse several orders of magnitude faster than XML configuration files, using testing and maintenance.
Disadvantages:
(1). Configuration information is dispersed, which is not conducive to centralized maintenance management.
(2). The change involves the source code of the program, need to find the source of the class, and must be compiled this step. The XML file may not need to find the source code, and it does not need to be recompiled.
6.JPA Note usage considerations:
JPA Annotations Support field annotations, as well as attribute annotations.
field annotation: Add annotations directly to the variable.
attribute annotation: Annotations are added to the Set/get method.
Note: No matter which annotation method is used, in an entity class, you cannot mix two annotation methods.
7.JPA Other common notes:
In addition to annotations such as @entity, @Id, @Table, @Column, @GeneratedValue, JPA has the following common annotations:
(1). @Temporal: Primarily for callout time types, 3 types of time are defined in the Javax.persistence.TemporalType enumeration:
A.date: equal to java.sql.Date;
B.time: equal to Java.sql.Time;
C.timestamp: equal to Java.sql.Timestamp;
(2). @Transient: All fields in the entity bean are mapped to the database by default, and you need to add that annotation if a property does not want to be mapped to the database.
(3). @Lob: To persist a property to a blob or CLOB type, a large data type.
(4). @Basic: General can be used to control whether to delay loading, sample usage:
Deferred loading: @Basic (Fetch=fetchtype.lazy)
Non-deferred loading: @Basic (Fetch=fetchtype.eager)
(5). @NamedQueryies and @namedquery: Define named Queries on entity beans.
The name query, similar to the preparestatement in JDBC, is a precompiled query in the database that can greatly improve query efficiency, as follows:
[Java] View plain copy
@NamedQueries ({
@NamedQuery (name= "named Query name", QUERY=JPQL query),
...
})
(6). @OneToOne:
One-to-one mapping annotation, a two-way one-to-one relationship needs to add the Mappedby attribute to the @onetoone annotation of the relational maintenance side (owner side), and the primary key column of the relationship maintenance side is established by the foreign key on the relational maintenance side (inverse side) when the table is built.
Usage: @OneToOne (optional=true,casecade=casecadetype.all,mappedby= "maintained side foreign key")
(7). @OneToMany:
A one-to-many mapping annotation, in a bidirectional one-to-many relationship, one end is the relational maintenance end (owner side), and only the mapped attribute can be added to the end. Multi-terminal is the relationship being maintained (inverse side). A primary key column on the relationship maintenance side (one end) is established by a foreign key on the maintenance side (multiport) when the table is built.
Usage: @OneToMany (mappedby = "Maintenance End (one end) primary key", Cascade=cascadetype.all)
Note: There is a term in hibernate called maintenance relationship inversion, where the other party maintains the relationship and uses Inverse=false to represent the relationship maintenance, and in the JPA annotation, Mappedby is equivalent to Inverse=false, That is, mappedby to maintain the relationship.
(8). @manytoone:
Multi-pair mapping annotation, in a two-way one-to-many relationship, one end uses @onetomany annotations, and multiple parties use @manytoone annotations. The multiple-pair annotation usage is simple, it does not maintain the relationship.
Usage: @ManyToOne (optional = false, Fetch = Fetchtype.eager)
(9). @ManyToMany:
Multi-Multiple mapping, using the mapping strategy of the middle table connection, the middle relation table is established to introduce two primary keys as foreign keys to form two many-to-many relationships. In a two-way many-to-many relationship, the Mappedby attribute is added to the @manytomany annotation of the relational maintenance end (owner side), the other party is the maintenance side of the relationship (inverse side), and the maintenance end of the relationship cannot add the Mappedby attribute, when the table is built, Generates an intermediate table based on a two-multiport primary key, and the foreign key of the middle table is a two-multiport primary key.
Usage: Relationship Maintenance end--> @ManyToMany (mappedby= "other party's relationship reference properties")
Relationship is maintained end--> @ManyToMany (cascade=cascadetype.all, fetch = Fetchtype.lazy)
8.JPA One-to-one correlation mapping:
The one by one correspondence between two entities in JPA is called One-to-one association mapping, such as human and identity card number relationships.
(1). One-to-one One-way association mapping:
Only the associated party can be found from the map side, not the reverse lookup.
Adds a @onetoone annotation on the associated map-side association property.
(2). One-to-one Bidirectional Association mapping:
Entities that can find associated relationships in both directions.
Relationship Maintenance side: Adds a @onetoone annotation to an associated property or field, while developing the Mappedby property of the @onetoone annotation.
Relationship is maintained: Adds a @onetoone annotation to the associated property or field.
9. Two strategies for one-to-one correlation mapping:
(1). One-to-one PRIMARY Key Association:
In one-to-one association mappings, the primary Key association policy does not add foreign key fields to the database tables corresponding to two associated entities, and the tables of two entities share the same primary key (the primary key is the same), and one entity's primary key is both a primary key and a foreign key.
Primary Key Association mapping: Adds a @primarykeyjoincolumn annotation (added to any end of an entity on a one-to-one annotation association map) while adding a @onetoone annotation on an Entity association property or method.
(2). One-to-one unique Foreign Key association:
In one-to-one relational mapping, a unique foreign key association policy adds a foreign key field to the corresponding database table in one entity to the primary key of another entity table and is the most commonly used mapping strategy in a one-to-one mapping relationship.
Unique Foreign Key Association: Adds a @joincolumn (name= "datasheet column name", unique=true) annotation while adding a @onetoone annotation to the associated property or field.
10. One-to-many Association Mapping:
In JPA, a one-to-many relationship between two entities is called a one-to-many relational mapping, such as class and student relationships.
(1). One-to-many One-way Association mapping:
In a One-to-many one-way association mapping, JPA automatically generates the Public intermediate Table Record association relationships in the database.
Add a @onetomany annotation on one end of the associated collection property or field.
(2). One-to-many Two-Way Association mapping:
In a one-to-many two-way Association map, JPA does not generate public intermediate tables in the database.
Adds a @onetomany annotation on one end of the associated collection property or field, specifying its Mappedby property.
Adds a @manytoone annotation to a multiport association property or field.
Note: In a one-to-many relationship map, Mappedby can only be added to the onetomany annotation, that is, the foreign key is generated in the multiport.
11. Multi-pair multi-correlation mapping:
In JPA, there is a many-to-many relationship between two entities called Many-to-many Association mappings, such as student and teacher relationships.
(1). Multiple to multiple one-way mapping:
Add a @manytomany annotation to the associated property or field on either of these entities.
(2). Multi-pair multi-directional mapping:
Adds a @manytomany annotation to a relationship maintenance-side associated property or field, specifying the Mappedby property of the annotation.
The relationship is added to the @manytomany annotation on the associated property or field of the maintenance side.
Entity inheritance mapping policy in 12.JPA:
In JPA, there are three mapping strategies for entity inheritance relationships: one-table inheritance policy, joined policy, and Table_per_class policy.
(1). single-Table inheritance policy:
Single-table inheritance policy, parent-class entities and subclass entities share a database table in which different categories of entities are distinguished by a list of distinguished fields. The following are specific practices:
A. Add the following annotation under the @entity annotation of the parent entity:
[Java] View plain copy
@Inheritance (strategy=inheritancetype.single_table)
@DiscriminatorColumn (name= "distinguished field Column name")
@ Discriminatorvalue (Parent Entity Distinguished Field column value)
B. Add the following annotation under the @entity annotation of the subclass entity:
[Java] View plain copy
@DiscriminatorValue (Subclass entity identifies field column values)
(2). Joined policy:
Joined policy, the parent class entity and the subclass entity correspond to the different tables in the database, and only the special attributes of their extensions exist in the table of the subclass entity, and the public properties of the parent class are kept in the parent Class entity mapping table. Specific practices:
Simply add the following annotation under the @entity annotation of the parent class entity:
[Java] View plain copy
@Inheritance (strategy=inheritancetype.joined)
Child class entities do not require special instructions.
(3). Table_per_class Policy:
Table_per_class policy, parent class entity and subclass entity each class corresponds to a table in a database, and all attributes are saved in the subclass table, including properties inherited from the parent class entity. Specific practices:
Simply add the following annotation under the @entity annotation of the parent class entity:
[Java] View plain copy
@Inheritance (Strategy=inheritancetype.table_per_class)
Child class entities do not require special instructions.
* Statement: Although it is 2010, or thank Yumbo Master http://blog.csdn.net/chjttony/article/details/6086298