【发布时间】:2012-04-10 10:17:25
【问题描述】:
我有一个使用 Hibernate 的 Web 应用程序,我正在尝试持久化一些数据,但尽管使用了 @Transactional 注释,但它未能在事务中持久化。
我的服务类如下:
@Service("profileService")
public class ProfileService {
private EntityManager entityManager;
@Autowired
private AccountService accountService;
@Autowired
private ProfileDAOImpl profileDao;
@PersistenceContext
public void setEntityManager(EntityManager em) {
this.entityManager = em;
}
@Transactional
public void addConnectionToAccount(SocialConnection sc) {
entityManager.persist(sc);
}
}
addConnectionToAccount() 方法是从另一个 Spring bean 以普通方法调用的,并且 ProfileService 类当前正在那里注入:
public class HibernateConnectionRepository implements ConnectionRepository {
@Inject
private ProfileService profileService;
@Override
@Transactional
public void addConnection(SocialConnection sc) {
try {
profileService.addConnectionToAccount(accountId, sc);
} catch (Exception e) {
e.printStackTrace();
}
}
我尝试将@Transactional 注释放在调用方法上,但徒劳无功。
以前我遇到过这样的问题,因为被持久化的对象不满足表限制(例如不可为空的列为空),或者因为该方法是从同一个类中调用的,而调用方法不是事务性的,但这里都不是这种情况..
有什么想法吗?它只是默默地失败,日志如下:
2012-03-26 22:25:04,702 [http-bio-8085-exec-9] DEBUG com.mchange.v2.resourcepool.BasicResourcePool - trace com.mchange.v2.resourcepool.BasicResourcePool@1bc25c8 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@e5b006)
2012-03-26 22:25:04,710 [http-bio-8085-exec-9] DEBUG org.hibernate.SQL - select SEQ_COUNT from SEQUENCE where SEQ_NAME = 'PO_SEQ' for update
2012-03-26 22:25:04,711 [http-bio-8085-exec-9] DEBUG org.hibernate.SQL - update SEQUENCE set SEQ_COUNT = ? where SEQ_COUNT = ? and SEQ_NAME = 'PO_SEQ'
2012-03-26 22:25:04,723 [http-bio-8085-exec-9] DEBUG com.mchange.v2.resourcepool.BasicResourcePool - trace com.mchange.v2.resourcepool.BasicResourcePool@1bc25c8 [managed: 3, unused: 2, excluded: 0] (e.g. com.mchange.v2.c3p0.impl.NewPooledConnection@e5b006)
2012-03-26 22:25:04,723 [http-bio-8085-exec-9] DEBUG org.hibernate.event.internal.AbstractSaveEventListener - Generated identifier: 2200, using strategy: org.hibernate.id.MultipleHiLoPerTableGenerator
更新
还想提一下,HibernateConnectionRepository bean 没有注释,实际上是在 @Configuration 类中配置的(如果这有什么不同?没有使用太多 @Configuration 类)。
创建bean的方法如下:
@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
ApplicationUser user = (ApplicationUser) authentication.getPrincipal();
return usersConnectionRepository().createConnectionRepository(String.valueOf(user.getAccountId()));
}
bean 的作用域是登录用户,但也可以为每个用户创建多次..
【问题讨论】:
标签: spring hibernate transactions