我有以下代码,包含所有必要的详细信息:
// This method is in UserService, marked with @Transactional
// Called when we insert a new user into the application.
// MySQL DB tables are: `user` and `user_attempt`
// ISOLATION LEVEL = READ-COMMITTED
@Override
public void insert(User entity) {
// user_attempt has no knowledge of user
UserAttempt uA = instanceNewUserAttempt();
userAttemptDao.insertEntity(uA); // uA is assigned an AUTO_INCREMENT from MySql
// Unidirectional
// @OneToOne(fetch = FetchType.LAZY, optional = false)
// @JoinColumn(name = "user_attempt_id", nullable = false)
// private UserAttempt userAttempt;
entity.setUserAttempt(uA);
// No locks until here
super.insert(entity); // Now here 2 locks are generated in the DB, why?
// Code blocks and does not go further. super just calls em.persist(...)
}
P.S。对我来说,瀑布不是解决方案!
编辑1
编辑2
试图调试Hibernate,这个块确实发生在org.hibernate.dialect.identity.GetGeneratedKeysDelegate:
内的这行代码中session.getJdbcCoordinator().getResultSetReturn().executeUpdate( insert );
编辑3
将代码更改为如下所示,现在它可以正常工作,但现在不同的是,在DB for User中我必须将user_attempt_id设置为允许NULL,这在概念上不可能发生,因为User和UserAttempt必须仅以组合形式存在: / p>
// This method is in UserService, marked with @Transactional
// Called when we insert a new user into the application.
// MySQL DB tables are: `user` and `user_attempt`
// ISOLATION LEVEL = READ-COMMITTED
@Override
public void insert(User entity) {
UserAttempt uA = instanceNewUserAttempt();
userAttemptDao.insertEntity(uA);
super.insert(entity);
// Unidirectional
// @OneToOne(fetch = FetchType.LAZY)
// @JoinColumn(name = "user_attempt_id", nullable = true)
// private UserAttempt userAttempt;
entity.setUserAttempt(uA);
}
结论: