jpa hibernate mysql无级联插入实体死锁

q43xntqr  于 2021-07-03  发布在  Java
关注(0)|答案(0)|浏览(242)

我有以下代码和所有必要的细节:

// 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、 美国瀑布对我来说不是一个解决办法!
编辑1
添加了带有信息的新屏幕

编辑2
已尝试调试hibernate,但该块确实发生在org.hibernate.dialect.identity.getgeneratedkeysdelegate中的以下代码行:

session.getJdbcCoordinator().getResultSetReturn().executeUpdate( insert );

编辑3
将代码更改为如下所示,现在可以工作了,但现在的区别是,在db for user中,我必须将user\u attempt\u id设置为allow null,这在概念上不能发生,因为user和userattempt只能组合存在:

// 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);
}

结论:
如果我想在db中有notnull约束,那么我就不能按我想要的方式使用hibernate,它根本不起作用(意思是在同一交易中插入两个实体并标记关系)
如果我放弃了让db constraint not null for user\u attempt\u id并分别插入实体的想法,那么在同一个事务中,我做了这个关系,然后它就工作了,但是在db中是一个逻辑间隙。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题