SQL Mybatis别名AS的重要性(二)

我们在设计数据库表的时候, 一个字段多个单词,用"_"连接, 如, user_name.
而我们在代码中创建实体类的时候, 通常用驼峰命名法, 如 : userName.
这就造成了我们在写sql的时候, 因为名称不同, 找不到数据, 报空指针异常.

为了解决问题,有以下两种方式:

(一) 使用AS, 作为别名

xml文件:

<select id="getUserList" resultType="dto.UserDto">
    select id, user_id as userId, user_name as userName, phone, enable, created
    from t_user 
    where enable =1
</select>

对应的实体类:

package dto;

@Setter
@Getter
public class UserDto{
   private int id;
   private String userId;
   private String userName;
   private String phone;
   private int enable;
}

这种方法, 最常用, 但是如果如果对象的字段较多, 每次都要写AS别名, 就会比较麻烦,这就可以考虑第二种方法.

(二) 封装, 封装sql返回的对象

xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
       PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
       "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.mybatis.UserMybatis">

   //封装sql返回的对象
   <resultMap id="UserResultMap" type="dto.UserDto">
       <result column="id" property="id" jdbcType="INT"/>
       <result column="user_id" property="userId" jdbcType="VARCHAR"/>
       <result column="user_name" property="userName" jdbcType="VARCHAR"/>
       <result column="phone" property="phone" jdbcType="VARCHAR"/>
       <result column="enable" property="enable" jdbcType="TINYINT"/>
   </resultMap>

    <select id="getUserList" resultMap="UserResultMap">
   		select id, user_id, user_name, phone, enable, created
   		from t_user 
   		where enable =1
   </select>
</mapper>

对应的实体类:

package dto;

@Setter
@Getter
public class UserDto{
   private int id;
   private String userId;
   private String userName;
   private String phone;
   private int enable;
}

注意点:

后期如果实体类字段增加或减少, 在xml文件中的sql封装对象也要相应的增加或减少.
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值