mybatis 的Binding 测试如下: 测试代码:
@Test
void shouldExecuteBoundSelectMapOfBlogsById() {
try (SqlSession session = sqlSessionFactory.openSession()) {
BoundBlogMapper mapper = session.getMapper(BoundBlogMapper.class);
Map<Integer,Blog> blogs = mapper.selectBlogsAsMapById();
assertEquals(2, blogs.size());
for(Map.Entry<Integer,Blog> blogEntry : blogs.entrySet()) {
assertEquals(blogEntry.getKey(), (Integer) blogEntry.getValue().getId());
}
}
}
mapper 接口文件:
@Select({ "SELECT * FROM blog"})
@MapKey("id")
Map<Integer,Blog> selectBlogsAsMapById();
接着就是实现文件: 测试如下: 如果我们mapper 文件写错了,会怎么样呢? 如下:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="wrong.namespace">
<select id="get" resultType="string">
select 1
</select>
</mapper>
接口方法:
public interface WrongNamespaceMapper {
void get();
}
断言抛出了runtimeException:
@Test
void shouldFailForBothOneAndMany() {
Configuration configuration = new Configuration();
Assertions.assertThrows(RuntimeException.class, () -> {
configuration.addMapper(MapperWithOneAndMany.class);
});
}
那么我们如上的命名空间写错了,怎么办呢? 这里也会抛出异常。
同理:丢失了命名空间也是错误的:
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper>
<select id="get" resultType="string">
select 1
</select>
</mapper>
测试文件如下:
@Test
void shouldFailForMissingNamespace() {
Configuration configuration = new Configuration();
Assertions.assertThrows(RuntimeException.class, () -> configuration.addMapper(MissingNamespaceMapper.class));
}
|