您的位置:首页 > 数据库

mybatis数据库字段名和实体类属性名不一致(四)

2019-03-11 19:20 232 查看

一、问题出现原因

      分析:如果数据库中有一些字段是user_name等复杂方式命名,而数据库实体类中的相应字段是username,这种情况常常会导致我们数据库语句查询不到报错,主要原因就是数据库字段映射不到实体类上,解决这个问题的方案主要有三种方式:

     1、在sql语句中使用别名:

[code]<select id="queryUserById" resultType="com.zpc.mybatis.pojo.User">
select
tuser.id as id,
tuser.user_name as userName,
tuser.password as password,
tuser.name as name,
tuser.age as age,
tuser.birthday as birthday,
tuser.sex as sex,
tuser.created as created,
tuser.updated as updated
from
tb_user tuser
where tuser.id = #{id};
</select>

       2、resultMap强制映射的方式解决

[code] <resultMap id="user" type="com.achuan.demo.entity.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="user_name" property="username" jdbcType="VARCHAR"/>
<result column="telephone" property="telephone" jdbcType="VARCHAR"/>
<result column="imax_email" property="iMaxEmail" jdbcType="VARCHAR"/>
<result column="sex" property="sex" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>

     3、驼峰匹配 — mybatis-config.xml 

          在mybatis全局文件中加入下面这个配置

[code]<configuration>
<!-- 开启驼峰映射 ,为自定义的SQL语句服务-->
<!--设置启用数据库字段下划线映射到java对象的驼峰式命名属性,默认为false-->
<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

</configuration>

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐