blog,blog,blog
blog,blog,blog在项目使用mybatis-guice
正文
如果你项目中使用的Spring 可能会用其中的ioc来配置mybatis。但是我们也可以选择官方出品的mybatis-guice 来使用ioc
使用maven配置依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-guice</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>4.1.0</version>
</dependency>
然后我们需要建立一个mybatisModule
官方有许多建立module的方法,这里我们使用 XMLMyBatisModule
代码如下
import com.google.inject.Guice; import com.google.inject.Injector; import org.mybatis.guice.XMLMyBatisModule;public class Init {
private static Injector injector;
static {injector = Guice.createInjector(new XMLMyBatisModule() { @Override protected void initialize() { setEnvironmentId("dev"); setClassPathResource("mybatis.cfg.xml"); } });}
public static Injector getInjector() { return injector; }}
假设你有个类调用了mapper 我们可以在类的进行注入,代码如下
import api.xxx.mapper.PersonMapper; import api.xxx.model.Person; import api.xxx.model.PersonExample; import com.google.inject.Inject;public class PersonService {
@Inject
private PersonMapper mapper;public boolean modifyInfo(Person person, String talentNo) { PersonExample example = new PersonExample(); example.createCriteria().andTalentNoEqualTo(talentNo); int result = mapper.updateByExampleSelective(person, example); return 1 == result; }}
调用代码 :
PersonService personService = Init.getInjector().getInstance(PersonService.class);
问答
问题1:我们的sqlSession 在哪里??
答:程序会自动调用 SqlSessionManager.openSession(ExecutorType execType) 其中ExecutorType 为SIMPLE。
@Overridepublic SqlSession openSession(ExecutorType execType) {
return sqlSessionFactory.openSession(execType);
}
问题2:sqlSession会关闭吗
答:程序在方法调用后会自动关闭session,调用SqlSessionManager.close()
@Override
public void close() {
final SqlSession sqlSession = localSqlSession.get();
if (sqlSession == null) {
throw new SqlSessionException("Error: Cannot close. No managed session is started.");
}
try {
sqlSession.close();
} finally {
localSqlSession.set(null);
}
}
问题3:怎么定义方法调用的sqlSession参数
答:通过@Transactional 可以定义sqlSession的参数。
官方教程
mybatis-guice:http://www.mybatis.org/guice/
