为什么冬眠立即执行身份插入

时间:2018-12-25 06:01:00

标签: java hibernate jpa

运行测试时,我在日志Executing identity-insert immediately中看到为什么要立即插入休眠模式?我希望在提交过程中插入。

On TransactionImpl creation, JpaCompliance#isJpaTransactionComplianceEnabled == false
begin
Executing identity-insert immediately

    /* insert MyJpaClass
        */ insert 
        into
            MyJpaClass
            (id, message) 
        values
            (null, ?)
Hibernate: 
    /* insert MyJpaClass
        */ insert 
        into
            MyJpaClass
            (id, message) 
        values
            (null, ?)
Natively generated identity: 1
HHH000387: ResultSet's statement was not registered
committing
Processing flush-time cascades
Dirty checking collections
Flushed: 0 insertions, 0 updates, 0 deletions to 1 objects
Flushed: 0 (re)creations, 0 updates, 0 removals to 0 collections
Listing entities:
MyJpaClass{id=1, message=text}
Initiating JDBC connection release from afterTransaction
Initiating JDBC connection release from afterTransaction

这是我的测试示例 Persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_2_0.xsd"
  version="2.0">
<persistence-unit name="HelloWorldPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>

    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
        <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;MODE=MySQL;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"/>
        <property name="javax.persistence.jdbc.user" value="sa"/>
        <property name="javax.persistence.jdbc.password" value=""/>

        <property name="hibernate.show_sql" value="true"/>
        <property name="hibernate.format_sql" value="true"/>
        <property name="hibernate.use_sql_comments" value="true"/>
        <property name="hibernate.transaction.factory_class"
          value="org.hibernate.engine.transaction.internal.jta.CMTTransactionFactory"/>
        <property name="hibernate.id.new_generator_mappings" value="true"/>
        <property name="hibernate.connection.autocommit" value="false"/>
        <property name="hibernate.hbm2ddl.auto" value="create-drop"/>

    </properties>
</persistence-unit>
</persistence>

测试

import static org.junit.Assert.assertNotNull;

import java.io.FileNotFoundException;
import java.sql.SQLException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class PersistTest {
    Logger LOG = LogManager.getLogger(PersistTest.class);

    protected static EntityManagerFactory emf;
    protected static EntityManager em;

    @BeforeClass
    public static void init() throws FileNotFoundException, SQLException {
        emf = Persistence.createEntityManagerFactory("HelloWorldPU");
        em = emf.createEntityManager();
    }

    @AfterClass
    public static void tearDown(){
        em.clear();
        em.close();
        emf.close();
    }

    @Test
    public void testPersist_success() {
        em.getTransaction().begin();
        MyJpaClass o = new MyJpaClass();
        o.setMessage("text");
        em.persist(o);
        em.getTransaction().commit();

        assertNotNull(o.getId());
        LOG.debug(o.getId());
    }
}

实体

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class MyJpaClass {

    @Id
    @GeneratedValue (strategy= GenerationType.IDENTITY)
    private Long id;

    private String message;

    public Long getId() {
        return id;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

2 个答案:

答案 0 :(得分:0)

immediately中的Executing identity-insert immediately一词的意思是:

  

事件上下文是否需要立即访问标识符   方法执行后(如果没有,则插入后的样式ID   如果我们不在交易范围内,发电机可能会被推迟。

在进行事务处理时,在执行方法后立即需要标识符。因此,请立即为您提供。

isolation level上继续插入时,您可以访问或不访问其他会话中的数据。

答案 1 :(得分:0)

由于使用了GenerationType.IDENTITY,因此无需等待提交即可直接执行插入操作,因为您需要获取ID。并且为了获得ID,您必须在数据库中执行插入。

这就是为什么GenerationType.SEQUENCE效率更高,可以推迟插入并且您可以使用此策略启用批处理的原因。

有关差异策略的更多信息:https://vladmihalcea.com/hibernate-identity-sequence-and-table-sequence-generator/