@Transactional 在 Bean 内部调用的 public 方法:HHH000437

@Transactional on a public method called inside a Bean: HHH000437

我对 @Transactional 注释有奇怪的行为。该代码与 caller:

上的 @Transactional 配合使用效果很好
import org.springframework.transaction.annotation.Transactional;

private javax.persistence.EntityManager em;

@Transactional
public void caller(String login) {
    callee(login);
}

public void callee(String login) {
    user = new User(login);
    em.persist(user);
    userInfo = new UserInfo();
    userInfo.setUser(user);
    em.persist(userInfo);
}

但是下面的实现 returns 在第二个 em.persist error em.persist 被叫:

import org.springframework.transaction.annotation.Transactional;

private javax.persistence.EntityManager em;

public void caller(String login) {
    callee(login);
}

@Transactional
public void callee(String login) {
    user = new User(login);
    em.persist(user);
    userInfo = new UserInfo();
    userInfo.setUser(user);
    em.persist(userInfo); // ERROR: org.hibernate.action.internal.UnresolvedEntityInsertActions : HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities. 
}

返回错误:

org.hibernate.action.internal.UnresolvedEntityInsertActions : HHH000437: Attempting to save one or more entities that have a non-nullable association with an unsaved transient entity. The unsaved transient entity must be saved in an operation prior to saving these dependent entities.    
Unsaved transient entity: ([package.entities.User#<null>])  
Dependent entities: ([[package.entities.UserInfo#<null>]])  
Non-nullable association(s): ([package.entities.UserInfo.user])

有人有想法吗?

谢谢!

我认为这是因为 Spring 围绕您的 classes 创建代理 bean,并且只有代理的方法通过注释行为得到增强。当你注释一个私有方法时,它是从你的内部调用的 class 并且不能通过代理调用,导致注释被忽略。

@M。我认为 Deinum 是正确的,是我答案的更正版本。因此,只有带注释的方法具有事务支持,但如果通过 spring 代理调用,则 。如果像您一样从 bean 本身调用它,它将不起作用。

为了让它工作,你必须使用这样的东西

context.getBean(MyBean.class).callee(login);