[java framework] JPA -- JPA Foundation

1. JPA Core API Objects

1.1.Persistence persisted object

Persisitence is primarily used to create an EntityMangerFactory, which can create a corresponding EntityMangerFactory based on the persistence unit name passed in.

// Corresponding profile persistence-unit name="cn.yif.jpa02"
// Create an entity class management factory by persisting classes
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("cn.yif.jpa02");

1.2.EntityMangerFactory Entity Management Factory

EntityMangerFactory is a thread-safe object. In a project, only one EntityManger object is needed, corresponding to a database resource. EntityMangerFactory object is a heavyweight object. Creating and destroying EntityMangerFactory object is resource-intensive. It contains the configuration information of the database, all entities and relationships, predefined JPQL statements, secondary cache.

1.3.EntityManger Entity Management Objects

EntityManger provides operations related to persistence: add, delete, change, check, and so on. It is an insecure object for threads, so you should only use one thread at a time in your project to avoid multiple threads sharing.EntityManger is lightweight and does not require too many resources to create and destroy, it should be closed when used up.Create an EntityManger object for a request in the Web.

1.4. Transaction Transactions

There are two types of javax.persistence.EntityTransaction and javax.transaction.Transaction JTA transactions.

javax.persistence.EntityTransaction: Can only control transaction management for different tables in the same database, which is used in most cases.

 

javax.transaction.Transaction: Handles transaction management for different tables in different databases.Tomcat does not support JTA transactions by default (which can be solved by plug-ins) or requires a JavaEE server such as a jboss, weblogic server.

Scenarios for JTA transactions: such as cross-line transfers, transaction lists.

2. Primary Key Generation Strategy

There are two types of primary key implementations, natural primary key and proxy primary key.

Natural Primary Key: Indicates that a field with business significance is used as the primary key, such as ID number, mobile phone number, etc. as the natural primary key, and this field must be unique.

Note that @GeneratedValue, which is not defined in JPA, represents a natural primary key and sets its own primary key value before saving.

 

Proxy Primary Key: Primary keys generally have no meaning and are used to distinguish between different rows of data.

Four primary key generation strategies are provided in JPA: IDENTITY, SEQUENCE, TABLE, AUTO.

2.1.IDENTITY

IDENTITY means that the primary key increases by itself. When JPA configures the IDENTITY policy, it automatically sets the primary key to increase by itself+1, as follows:

//@Id Is a required comment that represents the primary key of the corresponding database
   @Id
   //GeneratedValue Represents a primary key generation policy
   //①IDENTITY: Represents self-growth,
   // Features: 1.The primary key must be a numeric type; 2.The database used must support self-increasing functionality;3.Using native database generation strategies, performance is high
   // 4.Support IDENTITY Database type: MySQL, SQL Server, DB2, Derby, Sybase, PostgreSQL
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Integer id;

2.2.SEQUENCE

SEQUENCE means that self-incrementing is a sequential way. Generally used in Oracle, a Domain creates a table corresponding to a sequence. Oracle does not support ID self-incrementing columns but uses a sequence mechanism to generate primary key IDs.

//②SEQUENCE: sequence
    //Features: 1.The primary key must be a numeric type; 2.The database used must support sequences; 3.High performance using native database generation strategies
    //4.A sequence is created by default, and its name is called: HIBERNATE_SEQUENCE,All Domain This sequence is used by default. ID Self-increasing from this sequence
    //Use Name SEQ Specific sequence
    @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "SEQ")
    //name: The name of the sequence generator, which will be@GeneratedValue References in
    //sequenceName Will correspond to the name of the sequence in the real database OIDDOMAIN_SEQUENCE,Create a name in the database named OIDDOMAIN_SEQUENCE Sequence of
    //If the name of the sequence generator is not specified sequenceName = "OIDDOMAIN_SEQUENCE",
    //Then use the default sequence generator provided by the manufacturer, such as Hibernate The default sequence name provided is HIBERNATE_SEQUENCE
    @SequenceGenerator(name = "SEQ", sequenceName = "OIDDOMAIN_SEQUENCE")
    private Integer id;

Databases that support SEQUENCE: Oracle, Post greSQL, DB2.

2.3.TABLE

TABLE supports all database types and can be used in real projects if the database is not determined earlier.

//③TABLE(High and low)
    //Features: 1.The primary key must be a numeric type; 2.Supports all database types (using the default sequence); 3.Ultra low performance, queries and modifications per use (compatibility sacrifice)
    //If you do not use a table generator, the default table will be used,such as Oracle Use HIBERNATE_SEQUENCE
    @TableGenerator(name = "SEQ", table = "OidDomain_TABLE", pkColumnName = "SEQUENCE_NAME", valueColumnName = "SEQUENCE_COUNT", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "SEQ")
    private Integer id;

2.4.AUTO

//④AUTO Automatically select the appropriate strategy based on the specific database, which can be TABLE/SEQUENCE/IDENTITY One of
   //If the database is Oracle,Then choose Display Configuration Sequence,Do not use default sequence configuration
   //If the database is MySQL,Then choose Identity
   //If not specified, this is the default primary key generation policy
   @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

3. JPA persistent object state

There are four states of persisted objects in JPA: transient state, persistent state, managed state, detached state, offline state, deleted state.

Temporary state: Indicates that the object has just been created with a new statement and has no relationship with EntityManager.Not persisted, not in EntityManager.

Persistence state: Indicates that the object has a relationship with the EntityManager and is added to the EntityManager's first level cache where there is data.

Free state: This object is dissociated from the EntityManager and has been persisted, but is not in the EntityManager.

Delete status: The EntityManager.remove() method was called, the object has an associated ID, and under the administration of EntityManager, it may be scheduled to be deleted, and the transaction is actually deleted after commit commits.

3.1. Dirty data update

Dirty data: A persisted object in transaction management occurs when a transaction accesses and modifies data, but it has not yet been committed to the database. This uncommitted data is called dirty data.

When dirty data is merge executed in JPA, it does not matter whether the merge method is called or not, and when a transaction commit s, it is automatically updated to the database.

@Test
    public void JPAUpdate() {
        EntityManager entityManager = JPAUtil.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //The object taken from the database is a persisted object
        Employee employee = entityManager.find(Employee.class, 1);
        employee.setName("Modifier Haha");
        employee.setAge(223);
        //Perform modifications
        //In the state where the object is persisted, use merge Method, regardless of modification, will modify the database whether called or not
        //entityManager.merge(employee);
        //When submitting, it will query the database for this employee,If changed, execute merge Update data
        //That is commit Execute when necessary sql,This process is called dirty data update (dirty data once persisted data objects are modified)
        transaction.commit();

        JPAUtil.close(entityManager);
}

3.2. Dirty data update execution process

Get the entityManager object and start the transaction;

(2) Query the corresponding persisted object from the database through the entityManager object, which will be put into the first level cache, and JPA will prepare a snapshot of the current object (equivalent to making a backup of the object);

(3) Before committing a transaction, JPA will compare the current snapshot object with the object queried in the database. If it is the same, no modifications will be required and no corresponding merge SQL will be sent for modifications; if the comparison finds a difference, JPA will assume that the data is dirty now and that the dirty data will be sent merge when the transaction is committed.SQL statements synchronize database data.

3.3.Persist vs. Merge

@Test
    public void JPAPersistOrMerge() {
        Employee employee = new Employee("Creator 001", 20);
        EntityManager entityManager = JPAUtil.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        /**
         *  persist: The object placed in the method becomes a persisted object, changing the original object (which is in the first level cache)
         */
        entityManager.persist(employee);
        employee.setName("Update creator 001");
        transaction.commit();
        JPAUtil.close(entityManager);
    }

Two SQL statements are executed: the insert statement is sent first, and the update statement is sent for dirty data updates.

 

 

@Test
    public void JPAPersistOrMerge() {
        Employee employee = new Employee("Creator 001", 20);
        EntityManager entityManager = JPAUtil.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        /**
         *  merge: The object placed in the method does not become a persisted object, but it returns a persisted object, and modifying the persisted object takes effect as well.
         */
        //entityManager.persist(employee);
        Employee employee1 = entityManager.merge(employee);
        employee1.setName("Update creator 001");
        transaction.commit();
        JPAUtil.close(entityManager);
    }

Performing the same action will send two SQL statements:

 

 

3.4. Use of Remove

Whether remove in JPA deletes data directly, but modifies the state of an object to be deleted. When a transaction commit s, a delelte SQL statement is sent, which corresponds to the removal of dirty data from the data.

@Test
public void JPARemove() {
      EntityManager entityManager = JPAUtil.getEntityManager();
      EntityTransaction transaction = entityManager.getTransaction();
      transaction.begin();
      /**
       * remove Instead of deleting the data directly, modify the state of a persisted object to be deleted (planned deletion)
       * There can only be one entityManager, and the persistence state of other entityManager objects is not available here
       */
      Employee employee = entityManager.find(Employee.class, 7);
      entityManager.remove(employee);
      transaction.commit();
      JPAUtil.close(entityManager);
}

Tags: Java Database SQL Oracle MySQL

Posted on Sat, 02 May 2020 16:26:24 -0700 by ShibSta