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封裝對象也要相應的增加或減少.
發佈了55 篇原創文章 · 獲贊 12 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章