Mybatis——實體類屬性名和數據庫字段名不同時的解決方案


數據庫的字段:

對應的實體類:

 

 

方案一:

在XML映射文件中使用的resultMap,優點:可以被重復使用。

<resultMap id="BaseResultMap" type="com.dao.entity.UserInfoEntity">
    <!-- 用id屬性來映射主鍵字段 -->
    <id column="_id" jdbcType="VARCHAR" property="id" />
    <!-- 用result屬性來映射非主鍵字段 -->
    <result column="name" jdbcType="VARCHAR" property="name" />
</resultMap>

通過里面的id標簽和result標簽來建立映射關系,由property和column分別指定實體類屬性和數據表的列名。

方案二:

讓字段的別名與實體類的屬性名相同,優點:操作簡單,容易理解。缺點:當這樣的語句出現的次數過多的時候,到時冗余代碼增多,這些別名不能重用。

<select id="selectAll" resultType="com.dao.entity.UserInfoEntity">
    select _id id, name, age from user
</select>

 

@Select("select _id id, name, age from user")
List<UserInfoEntity> selectAll();

 

方案三:

使用Map集合封裝結果集,在MyBatis中字段名作為key,字段所對應的數據作為value。優點:可以在多表操作時使用。

<select id="selectUserAll" resultType="java.util.Map">
    select * from user
</select>

方案四:

使用注解@Results和@Result

這兩個注解與XML文件中的標簽相對應: @Results對應resultMap @Result對應result

@Select("select * from user where name = #{name}")
@Results({
  @Result(property = "id", column = "_id"),
  @Result(property = "name", column = "name")
})
UserInfoEntity getUserByName(@Param("name") String name);
@Select("select * from user where name = #{name}")
@Results(id = "userMap", value = {
  @Result(property = "id", column = "_id"),
  @Result(property = "name", column = "name")
})
UserInfoEntity getUserByName(@Param("name") String name);

@Select("SELECT * FROM user")
@ResultMap("userMap") //公用@Results
List<UserInfoEntity> findUserAll();

方案五:

通過配置屬性來完成映射,Mybatis給我們提供了一種映射方式,如果屬性的命名是遵從駝峰命名法的,數據列名遵從下划線命名,  那么可以使用這種方式,類似如下:

userName對應user_name;

userId對應user_id;

SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM