目录
实体类别名
在核心配置文件mybatis-config.xml中配置
"com.ucloud.brandcrud01.pojo":为实体类包名
<typeAliases>
<package name="com.ucloud.brandcrud01.pojo"/>
</typeAliases>
<select id="selectAll" resultType="dept">
</select>
解决表的列名和实体类属性名不一致
第一种: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"></include> from tb_brand
</select>
第二种:使用resultMap,column:表字段名,property:属性名
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<select id="selectAll" resultType="brand" resultMap="brandResultMap">
select * from tb_brand;
</select>
实体类属性名和数据库表列名不一致时,不能自动封装数
参数占位符
推荐 :#{} :执行SQL时,会将 #{} 占位符替换为 ?,将来自动设置参数值。底层使用的是 PreparedStatement。
${} :拼接SQL。底层使用的是 Statement ,会存在SQL注入问题。
SQL语句中特殊字段处理
可以看出报错了,因为映射配置文件是xml类型的问题,而 > < 等这些字符在xml中有特 殊含义,所以此时我们需要将这些符号进行转义。
< 就是 < 的转义字符。
动态SQL
多条件查询
<select id="selectByCondition" resultMap="brandResultMap">
select * from tb_brand
<where>
<if test="companyName!=null and companyName!=''">
and company_name like #{companyName}
</if>
<if test="brandName!=null and brandName!=''">
and brand_name like #{brandName}
</if>
</where>
</select>
单个条件查询
choose 标签类 似于Java 中的switch语句。
<select id="selectByConditionSingle" resultMap="brandResultMap">
select * from tb_brand
<where>
<choose>
<when test="companyName!=null and companyName!=''">
company_name like #{companyName}
</when>
<when test="brandName!=null and brandName!=''">
brand_name like #{brandName}
</when>
</choose>
</where>
</select>
修改
<update id="update">
update tb_brand
<set>
<if test="brandName != null and brandName != ''">
brand_name = #{brandName},
</if>
<if test="companyName != null and companyName != ''">
company_name = #{companyName},
</if>
<if test="ordered != null">
ordered = #{ordered},
</if>
<if test="description != null and description != ''">
description = #{description},
</if>
<if test="status != null">
status = #{status}
</if>
</set>
where id = #{id};
</update>
批量删除
<delete id="deleteByIds">
delete from tb_brand where id in
<foreach collection="array" item="id" separator=","
open="(" close=")">
#{id}
</foreach>
</delete>
foreach 标签 用来迭代任何可迭代的对象(如数组,集合)。
collection 属性: mybatis会将数组参数,封装为一个Map集合。
默认:array = 数组 使用@Param注解改变map集合的默认key的名称
item 属性:本次迭代获取到的元素。
separator 属性:集合项迭代之间的分隔符。 foreach 标签不会错误地添加多余的 分隔符。也就是最后一次迭代不会加分隔符。
open 属性:该属性值是在拼接SQL语句之前拼接的语句,只会拼接一次
close 属性:该属性值是在拼接SQL语句拼接后拼接的语句,只会拼接一次