mybatis的官方文档写得挺详细的,确很难找到入口,整理了一下;
最原始的用法
1String resource = "org/mybatis/example/mybatis-config.xml"; 2InputStream inputStream = Resources.getResourceAsStream(resource); 3SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 4 5SqlSession session = sqlSessionFactory.openSession(); 6try { 7 BlogMapper mapper = session.getMapper(BlogMapper.class); 8 Blog blog = mapper.selectBlog(101); 9} finally { 10 session.close(); 11}
结合Spring的用法
1<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 2 <property name="dataSource" ref="dataSource" /> 3</bean> 4<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 5 <property name="basePackage" value="org.mybatis.spring.sample.mapper" /> 6</bean>
结合了spring-boot的用法
自动检查DataSource,自动扫描查找带@Mapper注解的Mapper类,酸酸爽爽。