当我使用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)
}
}发布于 2013-10-23 09:35:05
它按照预期工作,因为没有人说,在事务未完成之前,插入不会在DB中生成。这样做的想法是JPA提供者(在您的例子中是Hibernate)决定何时对数据库进行刷新,而且在GenerationType.TABLE的情况下,它似乎决定在早期进行刷新。但是,由于进行了刷新,这并不意味着事务已经完成/完成:在持久化之后,您/或JPA提供程序可以回滚事务,并且该行将不再保留在DB中。
PS:我希望您有一些关于事务的背景(google隔离级别)和/或MySql的存储引擎(InnoDB是事务引擎,而MyIsam不是)。
https://stackoverflow.com/questions/19537617
复制相似问题