带有Guice注入的MyBatis Mapper的线程安全性



MyBatis-Guice建议我们可以注入Mapper,而不是直接使用SqlSession。从 https://mybatis.org/guice/injections.html

@Singleton
public class FooServiceMapperImpl implements FooService {
@Inject
private UserMapper userMapper;
@Transactional
public User doSomeBusinessStuff(String userId) {
return this.userMapper.getUser(userId);
}
}

这似乎不是线程安全的,因为映射器是从 SqlSession 的一个实例创建的,该实例不是线程安全的。(参考: https://mybatis.org/mybatis-3/getting-started.html(

为了使它线程安全,这是一种更好的方法吗?

/** Thread safe implementation **/
@Singleton
public class FooServiceMapperImpl implements FooService {
@Inject
private SqlSessionFactory sqlSessionFactory;
@Transactional
public User doSomeBusinessStuff(String userId) {
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
return userMapper.getUser(userId);
}
}
}

是的。 你应该能够只使用

@Inject SqlSession session;

与以下

bind(SqlSessionManager.class).toProvider(SqlSessionManagerProvider.class).in(Scopes.SINGLETON);
bind(SqlSession.class).to(SqlSessionManager.class).in(Scopes.SINGLETON);

这将创建 SqlSession 并将其关联到本地线程。 如果您使用的是@Transactional,也不应手动打开会话,该会话应该已经为您打开了会话。

最新更新