JPA Advanced - transaction isolation mechanism

My website:
welcome to visit

Here Insert Picture Description # JPA Advanced - Transaction Isolation

JPQL inquiry

JPQL like SQL and query keywords are the same
the only difference is: JPQL is object-oriented

rule

JPA query language similar to sql

It can not appear inside the table names, column names, can only occur java class name, the property name, case sensitive

sql keyword appears is the same meaning, case-insensitive

Not write write select an alias select *

Affairs

Transaction four characteristics:

Atomicity

A set of operations indivisible (with the total death)

consistency

Dynamic operation result is consistent (energy conservation)

Isolation

Multiple threads simultaneously operate each has no influence

Endurance

After the changes will save the data into the database

Affairs issues arising

1. lost updates

A transaction when the transaction and B simultaneously modify the value of a certain row,

A value of the transaction will be submitted to 0 and buy something

Transaction value to 0 and B will submit, also bought one. At this value is 0, Transaction A updates made to the data will be lost. (Equivalent to two sold goods)

2. dirty read

Read uncommitted data, B data read transaction A transaction has not been committed, then the transaction rollback operation if an error occurs and B, then A read transaction is dirty data

3. Magic Reading

Inconsistent with the amount of data read many times before and after

A read operation is performed in the transaction, the total amount required two statistics, the total amount of the previous query data, then the total amount of the transaction B performs data operations and submit new data, this time A reading of the transaction before and statistics are not the same, it will produce a phantom read

4. Do not re-read

Read many times before and inconsistent data content

A transaction becomes 20 will read his own at the age of 18, then the operation continues, this time Transaction B modifies A transaction at the age of 20, submitted the transaction, the transaction A reads my age again

(The interview will ask) database transaction isolation mechanism (four kinds)

READ UNCOMMITTED (uncommitted read)

This level, the transaction changes, even if not committed, other transactions are also visible. Transaction can read uncommitted data, known as dirty read (Dirty Read), this level of performance is not much better than the other levels, but lacks many of the benefits of other levels, rarely use.

READ COMMITTED (read committed)
 This level is the default isolation level for most database systems (MySQL, but is not). A transaction from the beginning until submission, any changes made to the other transactions are not visible. This level is also called non-repeatable read (nonrepeatable read), because the two executions of the same query, you may get different results.

REPEATABLE READ (repeatable read)
 This level ensures that the result of reading the same record in the same transaction multiple is the same, but still can not solve another Magic Reading (Phantom Read) problems. Phantom read, referring to the record when a range of things in a reading, another transaction and insert a new record in this range, when the record range before the transaction is read again, it will produce magic line (Phantom row). XtraDB and InnoDB storage engine to solve the problem of phantom read by multi-version concurrency control (MVCC). Repeatable read is MySQL's default transaction isolation level.

ERIALIZABLE (serializable)
 the highest level of isolation, force the transaction serial execution, avoiding the problem of phantom read said earlier. But every time reading all need to share table-level locking, read and write will block each other

For isolation mechanism, we can usually use the default

The pessimistic

Plus the lock to the transaction, at the same time allowing only one thread into operation, if the transaction has not been released, it will cause other transaction is waiting for low efficiency, generally do not use

Optimistic locking

Always assume the best case, every time the data are to pick up other people think is not modified, it will not be locked, but when the update will determine what others during this time did not go to update the data, allowing simultaneous read take, but can not be modified

Use optimistic locking achieve a spike scene

Entity class

package com.ifueen.domian;

import javax.persistence.*;

@Entity
@Table(name = "shaky")
public class Shaky {
    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @Column(name = "num")
    private Integer num;

    @Version
    private Integer version;

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        if (num<0){
            throw new RuntimeException("商品已经抢完,请下次早点");
        }else {
            this.num = num;
        }
    }

    @Override
    public String toString() {
        return "Shaky{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Shaky() {
    }
}

test

package com.ifueen.test;

import com.ifueen.domian.Shaky;
import com.ifueen.util.JPAUtil;
import org.junit.Test;

import javax.persistence.EntityManager;

public class ShakyTest {

    /**
     * 测试秒杀
     */
    @Test
    public void test(){
        //第一次开启
        EntityManager jpa = JPAUtil.getJpa();
        jpa.getTransaction().begin();

        //第二次开启
        EntityManager jpa1 = JPAUtil.getJpa();
        jpa1.getTransaction().begin();


        //第一次查询
        Shaky shaky = jpa.find(Shaky.class, 1L);
        shaky.setNum(shaky.getNum()-1);

        //同时第第二个人查询
        Shaky shaky1 = jpa1.find(Shaky.class, 1L);

        //第一个人提交事务
        jpa.getTransaction().commit();
        jpa.close();

        shaky1.setNum(shaky1.getNum()-1);
        //第二个人提交事务
        jpa1.getTransaction().commit();
        jpa1.close();
    }


}

Published 87 original articles · won praise 7 · views 20000 +

Guess you like

Origin blog.csdn.net/f2315895270/article/details/102309974