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

时间:2015-01-15 16:22:19

标签: spring jpa transactional

我对 @Transactional 注释有奇怪的行为。该代码适用于调用者

上的@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);
}

但是以下实现在第二个 em.persist 上返回错误被调用者上的@Transactional:

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])

有人有想法吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

我认为这是因为Spring在您的类周围创建代理bean,并且只有代理方法通过带注释的行为得到增强。当您注释私有方法时,它会从您的类中调用,并且无法通过代理调用,从而导致注释被忽略。

@M。我觉得Deinum是对的,纠正了我的答案。因此,只有带注释的方法具有事务支持,但如果通过spring代理调用则仅 。如果你像bean一样从bean本身调用它,它就不会起作用。

为了实现这一点,你必须使用类似的东西

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