In recent years ORM (Object-relational Mapping) Object-relational mapping, which is the mapping of entity objects and database tables, the technology market people sound furor, unusually lively, sun in the full absorption of the existing excellent ORM framework design ideas, based on the development of a new JPA (Java Persistence API) specification. The JPA Java Persistence API is a standard ORM interface for Java EE 5 and is part of the EJB3 specification.
So what is JPA? JPA is the mapping of object-relational tables through JDK5.0 annotations or XML, and the persistence of runtime entity objects into the database.
The relationship between Hibernate and JPA and its implementation mechanism
The relationship between JPA and hibernate can simply be understood as JPA is the standard interface, and Hibernate is implemented. So how does hibernate achieve this relationship with JPA? Hibernate is mainly achieved through three components, and hibernate-annotation, Hibernate-entitymanager and Hibernate-core.
Hibernate-annotation is the basis for hibernate to support the annotation mode configuration, which includes the standard JPA annotation and the annotation of Hibernate's own special features.
Hibernate-core is the core implementation of Hibernate and provides all the core functions of hibernate.
Hibernate-entitymanager implements the standard JPA, which can be seen as an adapter between Hibernate-core and JPA, which does not directly provide ORM functionality, but rather encapsulates the hibernate-core. Make hibernate conform to JPA specifications.
The following highlights the main class and implementation of the Hibernate-entitymanager package.
Hibernatepersistence.java, implements the JPA Persistenceprovider interface, which provides createentitymanagerfactory and createcontainerentitymanagerfactory two method to create a Entitymanagerfactory object, both of which are the buildentitymanagerfactory methods of the called Ejb3configuration object. To parse the JPA configuration file Persistence.xml, and create the Entitymanagerfactory object.
The implementation of the Entitymanagerfactory object is the Entitymanagerfactoryimpl class, which has one of the most important ******* properties is sessionfactory, one of the core objects of hibernate. The most important method of this class is Createentitymanager, which returns the Entitymnagaer object, and the Sessionfactory attribute is passed into the method.
The implementation of the Entitymanager object is the Entitymanagerimpl class, which inherits from the Abstractentitymanagerimpl class, In the Abstractentitymanager class, there is an abstract method getsession to get Hibernate's Session object, which is exactly supported by this session object. The Entitymanagerimpl class implements all the methods of the JPA Entitymanager interface and completes the actual ORM operation.
In addition, the Queryimpl class in the Hibernate-entitymanager package implements the JPA query interface with the support of the Entitymanagerimpl The Transactionimpl uses Entitymanagerimpl support to implement the JPA Entitytransaction interface.
At this point, Hibernate has completed all of the support work for JPA through the Hibernate-entitymanager package.
Here we have to talk about what is called an entity, in accordance with the JPA specification, a domain object with ORM metadata is called an entity. It should have the following conditions:
1. The corresponding <entity> elements must be used in the javax.persistence.Entity annotation or XML mapping file;
2. You must have a constructor with no arguments, the class cannot be declared final, and the methods and properties that need to be persisted cannot be declared final;
3. If the entity object of the Free State needs to be passed as a value (as passed through the remote service interface of the session Bean), the serializable interface must be implemented;
4. Properties that require persistence, the access modifier cannot be public, it must be accessed through the entity class method.
The state of the entity
There are 4 states of the entity:
1. New state: Newly created Entity object, not having persisted primary key, not associated with a persistence context
2. Controlled state: already has persistent primary key and persistence context established contact
3. Free State: Has persistent primary key, but has not established contact with persistence context
4. Delete state: Has persisted primary key, has established the connection with the persistence context, but has already been scheduled to delete from the database
Let's try to make a JPA annotation of a domain object into an entity class:
@Entity (name="T_test") Public classTestImplementsserializable{@Id @GeneratedValue (Strategy=generationtype.table) @Column (name="id")*******intTestID; @Column (Name= "Uname", length=100) *******String uname; @Column (Name="password")*******String password; @Column (Name="Time") @Temporal (temporaltype.date)*******Date Logintime; //Omit Get/setter Method }
@ below for a description of the JPA annotations involved in the above code
@Entity: The domain object is labeled as an entity class, indicating that the class needs to be persisted to the database, by default the class name is the table name, and the table name is explicitly specified through the Name property, such as: Name= "t_test" means that the TEST is saved to the table T_test table.
@Id: The corresponding property is the primary key of the table
@GeneratedValue: The generation strategy of the primary key, specified by the Strategy property, by default, JPA automatically chooses a primary key generation strategy that best fits the underlying database, such as the identity of SQL Server:
MySQL corresponds to auto increment, which defines several strategies to choose from in Java.persistence.GenerationType:
1. : Table auto-Grow field, Oracle does not support this way; Identity
2. : JPA automatically selects the appropriate policy, which is the default option; auto
3. : This is not supported by MySQL, which generates a primary key and specifies the sequence name by @sequencegenerator annotations. Sequence
4. : A primary key is generated from a table, and the framework borrows the primary key by table emulation, which can be used to make it easier to migrate the database. TABLE
@Colunm (name= "uname"): the table field corresponding to the attribute. We do not need to specify the type of the table field, because JPA gets the type from the entity attribute based on reflection, and if it is a string type, we can specify the field length so that the DDL statement can be generated automatically.
@Temporal (temporaltype.date): If the attribute is a time type, because the data table has a more rigorous division of the time type, you must specify a specific time type. Three types of time are defined in the Java.persistence.TemporalType enumeration:
Date: Equals java.sql.Date;
Time: Equals Java.sql.Time;
TimeStamp: Equals Java.sql.Timestamp.
JPA for a class that has a parent- child relationship , you must declare a mapping policy for the inherited entity for the parent class, and for an inherited entity, Java.persistence.InheritanceType defines 3 mapping strategies:
single_table: Parent-child classes are saved in the same table and are distinguished by field values.
JOINED: The same part of the parent-child class is saved in the same table, the different departments are stored separately, and the complete data is obtained by connecting different tables.
Table_per_class: Each class corresponds to its own table, it is generally not recommended in this way.
Let's take a look at how the actual case is used.
Parent class Test
@Entity (name="test") @Inheritance (Strategy=inheritancetype.single_table)// Specify inheritance policy @DiscriminatorColumn (Name= "Types", discriminatortype=discriminatortype.integer,length=1)// Specifies that the field is types, the type is an integer length of 1 @DiscriminatorValue (Value= "1")// corresponds to the value of the specific entity public classimplements serializable{... }
Sub-class child
@Entity @DiscriminatorValue (value = "2") public class child extends test{ // If we do not want JPA to persist this property to the database, use that annotation @Transient ******* String tempstr; @Lob // lob Type field @Basic (fetch =fetchtype.lazy) // with lazy loading, Fetchtype.eager does not take @Column (name = "Postattach", Columndefinition= ******* String Postattach;}
It is also quite convenient to see the types of the parent-child data by field. As for the associated relationships that JPA provides, for example, one-to-many, many-to-many, and a corresponding annotations, interested friends can refer to the relevant help documentation.
These are all described in the JPA in the form of annotations for persistence, the following we take the form of XML metadata, XML metadata information named Orm.xml, placed in the Classpath Meta-inf directory. If you provide XML metadata description information, it overrides the annotation metadata information in the entity class
<?xml version= "1.0" encoding= "UTF-8"? ><entity-mappings xmlns= "http://Java.sun.com/xml/ns/persistence/orm "Xmlns= "http://www.w3.org/2001/XMLSchema-instance "xsi:schemalocation="http://Java.sun.com/xml/ns/persistence/ormhttp://java.sun.com/xml/ns/persistence/orm_1_0.xsd"version=" > "1.0 "< Package>com.test</ Package><entityclass= "Test" > <table name= "Test"/> <attributes> <id name= "id" > <column name= "id"/> < Generated-value strategy= "TABLE"/> </id> <basic name= "uname" > <column name= "uname" length= "a"/> </basic> <basic name= "Logintime" > <column name= "logintime"/> <temporal>DATE</temporal> </basic> </attributes></entity><entity-mappings>
It is also fairly straightforward to see the JPA metadata in XML form.
JPA Important API
The JPA interfaces are located in the Javax.persistence and Javax.persistence.spi two packages, and most of the APIs in the Javax.persistence package are persistent operation interfaces for annotation classes, Entitymanager, and query. The 4 API in the JAVAX.PERSISTENCE.SPI package is the JPA service layer interface
Entitymanager
Entity objects are managed by the entity manager, interacting through entitymanager and persistence contexts
There are two types of entity managers:
Container class: The container-type Entity manager is responsible for collaboration between the question manager by the container, and the Java EE application Server provides the managed entity manager.
Application-Type: The lifecycle of the entity manager is controlled by the application, and the application creates Entitymanager instances through Javax.persistence.EntityManagerFactoty Creaeentitymanager
Entitymanager of the API
void persist (Object entity)
With the Persist method, the new entity instance is converted to a controlled state, that is, when the transaction committing the persist () method is committed, the entity's data is saved to the database.
If the entity has been persisted, then calling the persist () method will not happen.
If you call the Persist () method on an entity that has been deleted, the deleted-state entity is converted to a controlled state
If you perform a persist () operation on an entity that is free, throw illegalargumentexception
After an entity calls the persist () method, all entities associated with it will perform a persistence operation
void Remove (Object entity)
Deletes a controlled state entity.
If an entity is declared as a cascade delete (Cascade=remove or cascade=all), the associated entity is also deleted
Calling the Remove () method on a newly-created or deleted-state entity is ignored
Call the Remove () method on an entity that is free, throws a illegalargumentexception, and the related transaction rolls back
void Flush ()
Synchronizing controlled Entity data to the database
T merge (t entity)
Persisting a free-state entity to a database and converting it to a controlled entity
T Find (Class entityclass.object PrimaryKey)
Queries the entity object with the primary key, Entityclass is the class of the entity, PrimaryKey is the primary key value
Eg:topic t = em.find (topic.class,1);
HIBERNATE+JPA (EXT)