项目场景:在做SSM项目,mybatis读取数据库中数据
问题描述
提示:这里描述项目中遇到的问题:
发现通过mybatis对数据库进行查操作时,通过toString()方法有些数据可以看到,有些显示’null’,并且是某一列
问题如图下所示
@Test
public void findAllStudent() throws IOException {
String resource = "mybatis-config.xml";
List<Guide> guides = null;
InputStream inputStream = null;
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
GuideMapper guideMapper = sqlSession.getMapper(GuideMapper.class);
guides =guideMapper.queryGuide();
for (Guide guide : guides) {
System.out.println(guide.toString());
}
}
}
原因分析:
pojo中的实体属性名与数据库中的序列不一致(pojo中的对应的属性名和数据库中列名的名字不一致)
1、类中命名
private String id;
private String name;
private String password;
private int superuser;
private int flag;
2、数据库中column命名
解决方案:
方法一:采用最原始的方法-------修改类中属性名与数据库一致
**将 pojo中的对应的属性名和数据库中列名的名字一致**
(属性名与列名不区分大小写,这里为了方便看就大写了)
private String Gid;
private String Gname;
private String password;
private int superuser;
private int flag;
方法二:ResultMap(也是为了解决pojo属性名不一致的问题)
结果集映射
<!--结果集映射,type就是要映射的对象-->
<resultMap id="GuideMap" type="Guide">
<!--column数据库中的字段,property实体类中的属性-->
<result column="Gid" property="id"/>
<result column="Gname" property="name"/>
<result column="password" property="password"/>
<result column="flag" property="flag"/>
<result column="superuser" property="superuser"/>
</resultMap>
<!-- 记住下面的是将reseltType改成了ResultMap,后面跟的参数就是上面的id值,-->
<select id="queryGuide" resultMap="GuideMap" >
/*定义sql*/
select * from tourguide.guide
</select>
总结
##运行截图
采用上述任意一种方法都可以,结果如图所示
1.ResultMap 元素是 MyBatis 中最重要最强大的元素
2.ResultMap 的设计思想是,对于简单的语句根本不需要配置显式的结果映射,而对于复杂一点的语句只需要描述它们的关系就行了。