从mvn repo官网查看mybatis-spring-boot-starter对应的各版本号,如图:

从mybatis-spring官网,查看集成Spring framework对应的版本匹配规则,如图:
mybatis-spring官网url: https://mybatis.org/spring/zh/index.html

结合1和2点,判断选择mybatis的集成版本为2.2.2(根据spring framwork和jdk对应版本去匹配mybatis相应版本,然后选择版本较新且使用相对较多的版本)

根据官网的集成文档进行相应的配置集成
配置mybaits的核心组件SqlSessionFactoryBean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| @Configuration @MapperScan("pers.xiaotian.sgg") class MyBatisConfig { @Autowired private DataSource dataSource;
@Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factoryBean.setDataSource(dataSource); factoryBean.setMapperLocations(resolver.getResources("classpath:mapperConfig/**.xml")); return factoryBean.getObject(); } }
|
创建对应表的xml文件和bean接口实例
1 2 3 4
| @Component interface UserMapper{ User selectOne(); }
|
1 2 3 4 5 6 7 8
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="pers.xiaotian.sgg.UserMapper"> <select id="selectOne" resultType="pers.xiaotian.entity.User"> select * from user </select> </mapper>
|
使用测试类进行测试验证
1 2 3 4 5 6 7 8 9
| public class Topic11 {
public static void main(String[] args) { ApplicationContext ioc = new AnnotationConfigApplicationContext("pers.xiaotian.sgg"); UserMapper userMapper = (UserMapper) ioc.getBean("userMapper"); System.out.println(userMapper.selectOne().toString());
} }
|
运行结果,如图:

解决userName数据未匹配的方式
sql语句设置别名,代码调整如下:
1 2 3 4
| <select id="selectOne" resultType="pers.xiaotian.entity.User"> select id, user_name userName, age from user </select>
|
运行结果,如图:

添加字段转换Mappper方式,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="pers.xiaotian.sgg.UserMapper"> <resultMap id="baseMap" type="pers.xiaotian.entity.User"> <id column="id" property="id" /> <result column="user_name" property="userName"/> <result column="age" property="age" /> </resultMap> <select id="selectOne" resultMap="baseMap"> select * from user </select> </mapper>
|
运行结果,如图:

SqlSessionFactoryBean里面配置对应映射关系,此配置设置后全局生效,代码如下:
1 2 3 4 5 6 7 8 9 10 11
| @Bean public SqlSessionFactory sqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factoryBean.setDataSource(dataSource); factoryBean.setMapperLocations(resolver.getResources("classpath:mapperConfig/**.xml")); org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration(); configuration.setMapUnderscoreToCamelCase(true); factoryBean.setConfiguration(configuration); return factoryBean.getObject(); }
|
运行结果,如图:
