JPA 2 / Hibernate / MySql GenerationType.AUTO



当我使用 GenerationType.IDENTITY 或 GenerationType.AUTO 作为我的表 ID 并且我将一个实体保留在事务中时,数据会立即插入,这在事务结束之前!!

我尝试更改GenerationType.TABLE,在我的MYSQL数据库中生成并执行新的关联DDL,现在它正在工作。有人可以解释我为什么吗?

提取:

@Table
@Entity
public class Foo implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, unique = true)
    private Long id;
        ...
}

@Repository
public class EntityDaoServiceImpl {
    @PersistenceContext
    protected EntityManager em;
        @Transactional
    public void testFooCreation() {
            Foo foo = new Foo();
            em.persit(foo);
            //at this point with the AUTO or IDENTITY strategie, 
            //i ve got an effective insert in base otherwise with the TABLE strategie, 
            //the insert is effective at the end of my transaction (the excepted behavior)
    }
}

它按预期工作,因为没有人说在事务未完成之前不会在数据库中进行插入。这个想法是 JPA 提供程序(在您的例子中为 Hibernate)自行决定何时刷新数据库,似乎在GenerationType.TABLE的情况下,它决定尽早刷新。但是,由于进行了刷新,这并不意味着事务已完成/提交:持久化后,您/或 JPA 提供程序可以回滚事务,并且该行将不会保留在数据库中。

PS:我希望你有一些关于事务的背景(谷歌的事务隔离级别)和/或MySql的存储引擎(InnoDB是一个事务引擎,MyIsam不是)。

最新更新