使用Spring中的Mybatis工具类SqlSessionTemplate 依然还要我们自己去使用SqlSessionTemplate 来获取Mapper,有些繁琐。

可以直接让Spring管理所有的Mapper对象,先让配置类扫描所有Mapper:

@Configuration
@ComponentScan("org.example.entity")
@MapperScan("org.example.mapper")
public class MainConfiguration {

现在就可以直接通过容器获取Mapper:

public static void main(String[] args) {
    ApplicationContext context = new AnnotationConfigApplicationContext(MainConfiguration.class);
    TestMapper mapper = context.getBean(TestMapper.class);
    System.out.println(mapper.getStudent());
}

但依然需要存在SqlSessionTemplate或是SqlSessionFactoryBean的Bean,否则会无法初始化(毕竟要数据库的链接信息)。

若想直接去掉Mybatis的配置文件,实现全注解配置,就需要使用SqlSessionFactoryBean 类:使用Spring实现Mybatis全注解配置