Database field names and attribute names are not the same bean class treatment program

1, or the bean class attribute name and attribute names from the database of the same name, or spend ResultMap or ParameterMap.


-<mapper namespace="ordermapper">

<!-- 根据id查询得到一个order对象,使用这个查询是查询不到我们想要的结果的,这主要是因为实体类的属性名和数据库的字段名对应不上的原因,因此无法查询出对应的记录 -->


<select resultType="com.test.bean.order" parameterType="int" id="getorderbyid">select * from orders where order_id=#{id} </select>`

<!-- 第一种方法根据id查询得到一个order对象,使用这个查询是可以正常查询到我们想要的结果的,这是因为我们将查询的字段名都起一个和实体类属性名相同的别名,这样实体类的属性名和查询结果中的字段名就可以一一对应上 -->


<select resultType="com.test.bean.order" parameterType="int" id="getorderbyid2">select order_id id,order_no no,order_price price from orders where order_id=#{id} </select>

<select parameterType="int" id="getorderbymap" resultMap="orderResultMap">select * from orders where order_id=#{id} </select>


-<resultMap id="orderResultMap" type="com.test.bean.order">

<!-- 用id属性来映射主键字段 -->


<id column="order_id" property="id"/>

<!-- 用result属性来映射非主键字段,column对应数据库中的属性名,property对应Bean类属性名 -->


<result column="order_no" property="no"/>

<result column="order_price" property="price"/>

</resultMap>

<!-- 查询得到男性或女性的数量, 如果传入的是0就女性否则是男性 -->


<select id="getUserCount" statementType="CALLABLE" parameterMap="getUserCountMap">CALL mybits.ges_user_count(?,?) </select>

<!--parameterMap.put("sexid", 0);parameterMap.put("usercount", -1); -->



-<parameterMap id="getUserCountMap" type="java.util.Map">

<parameter property="sexid" jdbcType="INTEGER" mode="IN"/>

<parameter property="usercount" jdbcType="INTEGER" mode="OUT"/>

</parameterMap>

</mapper>

2, in the mapper class to a bean property aliases, to be consistent with the database field names

<select id="selectUserById" resultType="User">
        select 
        id,
        user_name as userName,<!--不用在意大小写,Mybatis会先转换成大写再进行匹配  -->
        user_password as userPassword,
        from user
        where id = #{id}
</select>
 
Published 35 original articles · won praise 2 · Views 1380

Guess you like

Origin blog.csdn.net/weixin_41001497/article/details/104025147