1. 问题:如果实体类和数据库的列名不一致(两种解决方法)
实体类中成员变量的名称为:
private Integer userId;
private String userName;
private Date userBirthday;
private String userSex;
private String userAddress;
数据库的列名为:
2. 解决方法一:起别名
通过 id as userId 的方法起别名来解决。按如下修改后又可正常运行了。
<select id="findAll" resultType="com.itheima.domain.User">
<!--select * from user-->
select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user
</select>
3. 解决方法二:配置实体类属性名和查询结果列名的对应关系
IUserDao.xml 中配置为:
<!--配置实体类属性名和查询结果列名的对应关系-->
<resultMap id="userMap" type="com.itheima.domain.User">
<!--主键字段的对应-->
<id property="userId" column="id"/>
<!--非主键字段的对应-->
<result property="userName" column="username"/>
<result property="userAddress" column="address"/>
<result property="userSex" column="sex"/>
<result property="userBirthday" column="birthday"/>
</resultMap>
<!--配置查询所有-->
<!--resultType表示要封装到哪里去-->
<select id="findAll" resultMap="userMap">
select * from user
<!--select id as userId,username as userName,address as userAddress,sex as userSex,birthday as userBirthday from user-->
</select>
此处注意:要将 resultType 改成 resultMap=“userMap”,指定用 resultMap 中的结果映射来实现数据的封装。这个过程需要多解析一段xml,所以效率没有方法一的高,但是可以提升开发效率:因为后面的 findById和findByName 也只需要修改 resultType 即可。