5. Solve the problem of inconsistency between attribute names and field names
1. Specific examples
pojo entity class:
public class User {
private Integer uid;
private String username;
private String pwd;
}
Database corresponding fields:
Test output results:
@Test
public void getUserByID(){
SqlSession sqlSession;
try {
sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserByID(2);
System.out.println(user);
}finally {
MybatisUtils.closeSqlSession();
}
}
This happens when the fields are not aligned.
2. Solution
1. Make an alias
<select id="getUserByID" parameterType="int" resultMap="UserMap">
select uid,username,password as pwd from users where uid = #{id}
</select>
2、resultMap
Result set mapping
uid username pwd
uid username password
<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--colunm数据库中的字段,properties实体类中的属性-->
<result column="uid" property="id"/>
<result column="username" property="name"/>
<result column="password" property="pwd"/>
</resultMap>
<select id="getUserByID" parameterType="int" resultMap="UserMap">
select * from users where uid = #{id}
</select>
resultMap
Elements are the most important and powerful elements in MyBatis.- The design idea of ResultMap is to achieve zero configuration for simple statements, and for more complex statements, only the relationship between the statements needs to be described.
ResultMap
The best part is that although you already know it quite well, you don't need to use them explicitly.