使用Mybatis进行开发,javabean属性名和数据库表字段名不一致的三种处理方式

javabean属性

private int id;
    private String name;
    private String password;

数据库字段
在这里插入图片描述
其中,密码字段不一致。

有以下三种解决方式:
1. 通过对数据库字段起一个别名
2. 使用resultMap结果集进行映射
3. 使用注解对字段进行映射

通过对数据库字段起一个别名

简而言之,言而简之,在sql语句中对数据库表字段起别名为javabean属性名
示例代码如下:

<select id="getUserById" resultType="cn.yangyt.pojo.User">
        select id,name,pwd as password from mybatis.user where id=#{id};
</select>

使用resultMap结果集进行映射

在xxxMapper.xml文件中进行映射即可

<resultMap id="UserMap" type="User">
        <result column="pwd" property="password"></result>
</resultMap>

其中column为数据库表字段,property为javabean属性名

<select id="getUserList" resultType="cn.yangyt.pojo.User">
		select * from mybatis.user;
</select>

使用注解对字段进行映射

在接口前添加注解如下即可:

@Select("select * from user")
    @Results({
            @Result(property = "password",column = "pwd")
            }
    )
    List<User> getUserList();

初学Mybatis,如果哪里有错误的地方,还望各位指正!

猜你喜欢

转载自blog.csdn.net/qq_44713855/article/details/107574366