使用 MyBatis-Spring,你可以继续直接使用 MyBatis 的 API。仅仅在代码中使用 Spring 中的 SqlSessionFactoryBean 来创建一个 SqlSessionFactory。
public class UserMapperSqlSessionImpl implements UserMapper {
// SqlSessionFactory would normally be set by SqlSessionDaoSupport
private SqlSessionFactory sqlSessionFactory;
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
public User getUser(String userId) {
// note standard MyBatis API usage - opening and closing the session manually
SqlSession session = sqlSessionFactory.openSession();
try {
return (User) session.selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
} finally {
session.close();
}
}
}
小心使用此选项, 因为错误的使用会产生运行时错误, 或者更糟糕的数据一致性的问题。这些是告诫:
-
它不会参与到 Spring 的事务之中。
-
如果 SqlSession 使用 DataSource,它也会被 Spring 事务管理器使用,而且当前有事务在进行时,这段代码会抛出异常。
-
MyBatis 的 DefaultSqlSession 是线程不安全的。如果在 bean 中注入了它,就会发生错误。
-
使用 DefaultSqlSession 创建的映射器也不是线程安全的。如果你将它们注入到 bean 中,是会发生错误的。
-
你必须保证在 finally 块中来关闭 SqlSession。
浙公网安备 33010602011771号