JPA Hibernate MySQL插入没有级联的实体死锁

时间:2016-05-10 13:10:50

标签: java hibernate jpa java-ee locking

我有以下代码,包含所有必要的详细信息:

// 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(...)
}

Locks

P.S。对我来说,瀑布不是解决方案!

编辑1

添加了包含信息的新屏幕 enter image description here

编辑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);
}

结论:

  1. 如果我想在DB中有NOT NULL约束,那么我不能以我想要的方式使用Hibernate,它根本不起作用。 (意思是在同一事务中插入两个实体并标记关系)
  2. 如果我放弃了对user_attempt_id有DB约束NOT NULL并且单独插入实体的想法,那么在同一个事务中我做关系,然后它可以工作,但然后在DB中是一个逻辑间隙。

0 个答案:

没有答案