Http://blog.csdn.net/chjttony/article/details/6086298 1. JPA introduction:
The Java persistence specification is separated from the Entity Bean (Entity bean) before EJB2.x. After EJB3, Entity beans are no longer available, but put in JPA for implementation. JPA is an object persistence specification proposed by sun. Each JavaEE application server chooses its own implementation. The JPA designer is the author of The Hibernate framework. Therefore, Hibernate is the default implementation of JPA in the Jboss server, oracle Weblogic uses EclipseLink (previously called TopLink) as the default JPA implementation. IBM Websphere and Sun's Glassfish use OpenJPA (an open-source project of Apache) as its default JPA implementation by default.
The underlying implementation of JPA is some popular open-source ORM (object relationship Ing) Frameworks. Therefore, JPA is actually a ing between java object and relational database, use the idea of object-oriented programming to operate on the specifications of relational databases.
2. JPA persistence policy file:
According to the JPA specification, in the entity bean application, you need to add the persistent configuration file persistence. xml under the META-INF Directory of the application classpath, which is the persistence policy file. The content is as follows:
[Xhtml]View plaincopy
- <? 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 unit name" transaction-type = "JTA">
- <Jta-data-source> use JCA to deploy the data source JNDI on the javaEE server </jta-data-source>
- <! -- Specifies the JPA implementation provider. If this parameter is not specified, the default JPA provider of the JavaEE server is used. Here, we use OpenJPA as an example -->
- <Provider> org. apache. openjpa. persistence. PersistenceProviderImpl </provider>
- <Class> Full object bean path name </class>
- ......
- <Properties>
- <! -- Configure some information about the JPA implementation provider -->
- </Properties>
- </Persistence-unit>
- </Persistence>
Note: You can configure multiple persistence units in the persistence policy file. Multiple persistence units are often configured when you use distributed databases.
3. Entity Bean development:
The basic specification for Entity bean development defined in the JPA specification:
(1) add the "@ Entity" annotation on the Entity bean to identify the bean as the Entity bean.
(2). Entity beans must be serialized.
(3 ). use the @ Table (name = database Table name) annotation to identify the Table name mapped to the relational database by the entity bean. If this parameter is not specified, the JPA implementation will automatically generate the default Table name.
(4). There must be a primary key identified by the "@ Id" Annotation. For example, the auto-increment primary key is written as follows:
[Java]View plaincopy
- @ Id
- @ Column (name = "Column name ")
- @ GeneratedValue (Strategy = GenerationType. Auto)
- Private int id;
Note: The annotation @ Id and @ GeneratedValue must be used at the same time. After the annotation is identified, the generation policy for the primary key is required.
(5 ). other attributes of Bean use the "@ Column (name = Column name)" annotation to specify the Column name mapped to the database table. If this attribute is not specified, the default Column name is automatically generated in the JPA implementation.
(6) The Entity Bean must strictly follow the JavaBean specifications, provide default construction methods without parameters, and provide the set and get methods for attributes.
(7) it is best to override the hashcode () and equals () methods. The unique identifier of the Entity bean is the primary key. Therefore, use the primary key of the Entity bean for comparison.
4. Primary key generation policy of the object bean:
The annotation generation policy of the object bean uses the "@ GeneratedValue" annotation to specify the primary key generation policy. By default, the Auto increment policy is used. JPA does not support the UUID primary key generation policy of Hibernate, to use the UUID of Hibernate as the primary key, use the following method:
(1) add the Hibernate. annotation jar package to the class path.
(2) add the following annotations to the field "@ Id:
[Java]View plaincopy
- @ GeneratedValue (generator = "UUID primary key generation policy ")
- @ GenericGenerator (name = "UUID primary key generation policy", strategy = "uuid ")
5. Notes for JPA development:
JPA supports xml and annotation methods. Currently, with the increasingly mature and popular annotation methods, only the annotation method is used when developing JPA. Therefore, the Java EE 5 and later versions are required, because the previous versions do not support annotation.
Compared with xml files, java annotations have the following advantages and disadvantages:
Advantages:
(1). Reducing descriptors greatly improves development efficiency.
(2). Check during compilation. Errors are reported during compilation.
(3) annotations are in java code to avoid extra file maintenance work.
(4). The annotation is compiled into a java bytecode, which consumes less memory and reads faster. It is often resolved several orders of magnitude faster than the xml configuration file, and is tested and maintained.
Disadvantages:
(1). Scattered configuration information is not conducive to centralized maintenance and management.
(2) The change involves the source code of the program. You must find the source code of the class and compile it. In comparison, the xml file does not need to find the class source code, and does not need to be re-compiled.
6. Notes for using JPA annotations:
JPA annotations support field annotations and attribute annotations.
Field annotation: add annotation directly to the variable.
Attribute annotation: add annotation to the set/get method.
Note: No matter which annotation method is used, you cannot mix the two annotation methods in an object class.
7. Other Common Annotations of JPA:
In addition to annotations such as @ Entity, @ Id, @ Table, @ Column, and @ GeneratedValue, JPA also has the following common annotations:
(1) [email protected]: it is mainly used to mark the time type. Three time types are defined in the javax. persistence. TemporalType enumeration:
A. DATE: equivalent to java. SQL. Date;
B. TIME: equivalent to java. SQL. Time;
C. TIMESTAMP: equivalent to java. SQL. Timestamp;
(2) [email protected]: by default, all fields in the object bean will be mapped to the database. If a property does not want to be mapped to the database, add this annotation to it.
(3) [email protected]: permanent attribute to Blob or Clob type, for big data type.
(4) [email protected]: generally, it can be used to control whether to perform delayed loading. Usage example:
Delayed loading: @ Basic (fetch = FetchType. Lazy)
Non-delayed loading: @ Basic (fetch = FetchType. EAGER)
(5) [email protected] and @ NamedQuery: define the name query on the object Bean.
Name query is similar to the PrepareStatement in jdbc. It is a pre-compiled query in the database and can greatly improve the query efficiency. The usage is as follows:
[Java]View plaincopy
- @ NamedQueries ({
- @ NamedQuery (name = "name of the query", query = JPQL query statement ),
- ......
- })
(6) [email protected]:
One-to-one ing annotation. For a bidirectional one-to-one relationship, you must add the mappedBy attribute to the @ OneToOne annotation of the owner side. During table creation, the link is maintained at the inverse side) create a foreign key pointing to the primary key column at the link maintenance end.
Usage: @ OneToOne (optional = true, casecade = CasecadeType. ALL, mappedBy = "maintained end foreign key ")
(7) [email protected]:
One-to-multiple ing annotation. In a bidirectional one-to-multiple relationship, one end is the owner side, and the mapped attribute can only be added at one end. Multi-terminal is the inverse side ). When creating a table, a foreign key is set up at the link maintenance End (multi-terminal) to point to the primary key column at the link maintenance end (one end.
Usage: @ OneToMany (mappedBy = "maintenance end (one end) primary key", cascade = CascadeType. ALL)
Note: In Hibernate, there is a term called maintenance relationship inversion, that is, the other party maintains the association relationship. inverse = false is used to indicate the maintenance of the relationship. In the JPA annotation, mappedBy is equivalent to inverse = false, that is, mappedBy maintains the relationship.
(8). @ ManyToOne:
Multi-to-one ing annotation. In a bidirectional one-to-multiple relationship, one end uses the @ onetoworkflow annotation, and the other end uses the @ ManyToOne annotation. Multi-to-one annotation is easy to use, and it does not need to maintain the relationship.
Usage: @ ManyToOne (optional = false, fetch = FetchType. EAGER)
(9) [email protected]:
For multi-to-multi ING, the ing policy of the intermediate table connection is adopted. The established intermediate relationship table introduces the primary keys on both sides as foreign keys to form two multi-to-one relationships. In a bidirectional multi-to-multi-relationship, add the mappedBy attribute to the @ manytoedannotation of the owner side. The other side is the inverse side of the link ), the maintenance end of the link cannot add the mappedBy attribute. During table creation, an intermediate table is generated based on two multi-end primary keys. The foreign key of the intermediate table is two multi-end primary keys.
Usage: link maintenance end --> @ ManyToMany (mappedBy = "link reference attribute of the other party ")
Link maintenance end --> @ ManyToMany (cascade = CascadeType. ALL, fetch = FetchType. Lazy)
8. One-to-one association ing of JPA:
In JPA, two entities have one-to-one ing relationships, such as the relationship between people and ID card numbers.
(1). One-to-one association ING:
You can only find the associated party from the ing end, but not reverse lookup.
Add the @ OneToOne annotation to the ing attributes.
(2). One-to-one bidirectional association ING:
You can query the entities of an association in two directions.
Link maintenance end: add the @ OneToOne annotation to the association attribute or field, and specify the mappedBy attribute of the @ OneToOne annotation.
Link maintenance end: add the @ OneToOne annotation to the association attribute or field.
9. One-to-one association ing policies:
(1). One-to-one primary key Association:
In one-to-one association ING, the primary key association policy does not add a foreign key field to the database table corresponding to the two associated entities. The tables of the two entities share the same primary key (the primary key is the same ), the primary key of an object is both a primary key and a foreign key.
Primary key association ing: add the @ OneToOne annotation and the @ PrimaryKeyJoinColumn annotation to the object Association attribute or method (add the annotation to any end of the one-to-one annotation Association ing object ).
(2). One-to-one unique foreign key Association:
In one-to-one relationship ING, the unique foreign key association policy adds a foreign key field to the database table corresponding to one object to point to the primary key of another object table, it is also the most common ing policy in one-to-one ing relationships.
Unique Foreign key association: add @ OneToOne annotation to the association attribute or field, and add @ JoinColumn (name = "data table column name", unique = true) annotation.
10. One-to-multiple Association ING:
In JPA, two entities are one-to-many relationships called one-to-many association relationship ING, such as class-to-student relationships.
(1). One-to-many unidirectional Association ING:
In one-to-multiple one-way Association ING, JPA automatically generates a public intermediate table Record Association relationship in the database.
Add the @ onetoworkflow annotation to the link set attribute or field at one end.
(2). One-to-multiple bidirectional association ING:
In one-to-multiple bidirectional association ING, JPA does not generate a public intermediate table in the database.
Add the @ onetoworkflow annotation to an associated set attribute or field at one end, and specify its mappedBy attribute.
Add the @ ManyToOne annotation to the multi-terminal Association attribute or field.
Note: In a one-to-multiple relationship ING, mappedBy can only be added to the onetoworkflow annotation, that is, a foreign key is generated on multiple terminals.
11. Multi-to-multi-Association ING:
In JPA, two entities are multi-to-many relationships called multi-to-multi-Association mappings, such as the relationship between students and teachers.
(1). Many-to-many unidirectional ING:
Add the @ ManyToMany annotation to any object's associated attributes or fields.
(2). Many-to-many bidirectional ING:
Add the @ manytoyun annotation to the association attribute or field of the link maintenance end, and specify the mappedBy attribute of the annotation.
Add the @ ManyToMany annotation to the association attribute or field of the link to be maintained.
12. In JPA, the entity inherits the ing policy:
In JPA, there are three ing policies for object inheritance relationships: single-table inheritance policy, Joined policy, and Table_PER_Class policy.
(1). Single table inheritance policy:
Single-table inheritance policy. Parent-class entities and sub-class entities share a database table. In the table, a column is used to identify fields to differentiate entities of different classes. The procedure is as follows:
A. Add the following annotation under the @ Entity annotation of the parent class object:
[Java]View plaincopy
- @ Inheritance (Strategy = InheritanceType. SINGLE_TABLE)
- @ DiscriminatorColumn (name = "identifying field column names ")
- @ DiscriminatorValue (column value of the parent entity identification field)
B. Add the following annotation under the @ Entity annotation of the subclass object:
[Java]View plaincopy
- @ DiscriminatorValue (column value of the field to be recognized by the subclass object)
(2). Joined policy:
In the Joined policy, the parent object and the child object correspond to different tables in the database respectively. The child object table only has its extended special attributes, the public attributes of the parent class are stored in the parent class object ing table. Specific practices:
You only need to add the following annotation under the @ Entity annotation of the parent class object:
[Java]View plaincopy
- @ Inheritance (Strategy = InheritanceType. JOINED)
Special descriptions are not required for subclass objects.
(3). Table_PER_Class policy:
Table_PER_Class policy. Each class of the parent class object corresponds to a table in the database, and all attributes, including attributes inherited from the parent class object, are saved in the child class table. Specific practices:
You only need to add the following annotation under the @ Entity annotation of the parent class object:
[Java]View plaincopy
- @ Inheritance (Strategy = InheritanceType. TABLE_PER_CLASS)
Special descriptions are not required for subclass objects.
JPA learning notes 1--JPA basics (from CSDN)