mybati 字段映射

  Java中屬性命名通常使用駝峯命名法,mysql中的字段通常使用「_」來鏈接兩個單詞。例如mysql中通常都是 admin_id 而不是adminId,java程序中在dao層定義的話通常都是 adminId  經過駝峯法來命名字段。 java

  沒有處理的狀況下mysql字段和java中字段不匹配,經過SELECT 獲取不到數據。須要先經過字段映射,二字段映射通常有三種狀況mysql

1設置別名,返回列的別名和Model中的屬性一致,因此能夠映射。(通常不推薦,若是使用視圖能夠使用這個)

<select id="getOne"   resultType="User">
select id,user_name userName,user_pass userPass from sys_useer where id=#{id}
</select>

 

2設置resultMap,使返回列和Model中的屬性匹配 

 <?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="com.item.mapper.UserMapper">

<resultMap id="userMap" type="com.item.model.User">
<id property="id" column="id" />
<result property="userName" column="user_name"/>
<result property="userPass" column="user_pass"/>
</resultMap>

<sql id="Base_Column_List">
        id,user_name,user_pass
</sql>
<select id="getOne" resultMap="userMap">
        select
<include refid="Base_Column_List"/>
        from user where id=#{id}
</select>
</mapper>

3mybatis 駝峯映射

3.1在.properties/.yml(注意yml中不是一下格式)文件中添加

mybatis.configuration.map-underscore-to-camel-case=true 

3.2在mybatis的配置文件,如mybatis-config.xml中進行配置:

<configuration>
    <!--設置啓用數據庫字段下劃線映射到java對象的駝峯式命名屬性,默認爲false,true表示開啓-->  
    <settings>
      <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
 
</configuration>
相關文章
相關標籤/搜索