解决字段名与实体类属性名不同的2种方法
解决字段名与实体类属性名不同有2个方法:1.编写 sql 语句时,给字段名加上与实体类属性名一直的别名;2.在实体类文件中加入结果映射<resultMap>。以下对着2种方法进行举例。
一. 编写 sql 语句时,给字段名加上与实体类属性名一直的别名
OrderMapper.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="com.wsb.mybatis.beans.OrderMapper">
<select id="selectOrder" parameterType="int" resultType="Order">
SELECT
order_id id, order_no orderName, order_price price FROM orders WHERE
order_id = #{id}
</select>
</mapper>
二. .在实体类文件中加入结果映射
OrderMapper.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="com.wsb.mybatis.beans.OrderMapper">
<select id="selectOrder" parameterType="int" resultMap="OrderResultMap">
SELECT * FROM orders WHERE order_id = #{id}
</select>
<resultMap type="Order" id="OrderResultMap">
<id property="id" column="order_id"/>
<result property="orderName" column="order_no"/> <result property="price"
column="order_price"/>
</resultMap>
</mapper>