MyBatis-Guice建议我们可以注入SqlSession,而不是直接使用Mapper。来自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);
}
}
}发布于 2019-10-26 03:17:34
是。您应该能够只使用
@Inject SqlSession session;包含以下内容
bind(SqlSessionManager.class).toProvider(SqlSessionManagerProvider.class).in(Scopes.SINGLETON);
bind(SqlSession.class).to(SqlSessionManager.class).in(Scopes.SINGLETON);它将创建SqlSession并将其关联到本地线程。如果你正在使用@Transactional,你也不应该手动打开会话,因为它应该已经为你打开了一个会话。
https://stackoverflow.com/questions/58178235
复制相似问题