1、MyBatis执行sql语句时,实体类名和数据库列名不一致时:
方法1(起别名):
*起别名:对不一样的列名起别名,让别名跟实体类的属性名一样 缺点:每次查询都要定义一次别名
缺点:每一次查询都要定义一次别名
<select id="selectAll" resultType="brand">
select id,brand_name as brandName,company_name as companyName,ordered,description,status from tb_brand;
</select>
方法2(sql片段插入):
*sql片段
缺点:不灵活
例子:
<sql id="brand_column">
id,brand_name as brandName,company_name as companyName,ordered,description,status
</sql>
<select id="selectAll" resultType="brand">
select <include refid="brand_column" /> from tb_brand;
</select>
方法3(resultMap标签):
*resultMap:
定义resultMap标签,
resultMap中有两个属性
(1)id:完成主键字段的映射
(2)result:完成一般字段的映射 这两个属性都含有column:表的列名,property:实体类的属性名
<resultMap id="userResultMap" type="user"> id:唯一标识 type:映射的类型,支持别名
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
在<select>标签中,使用resultMap属性替换resultType属性
<select id="selectAll" resultType="userResultMap">
select * from user;
</select>
2、关于sql参数占位符的使用和特殊字符的处理
在SQL语句中,会用到一些参数以及标准符号的使用,如下面sql语句:
<select id="selectById" resultType="user">
select * from user where uid = #{uid};
</select>
#{uid} 就是参数占位符,= 就是特殊符号。
特殊字符处理:
1.转义字符: < 符号相当于: < 2.CDATA区: < 符号相当于: <![CDATA[ < ]]>