在使用Mybatis的时候,我们将查询语句写入.xml文件中,那具体的xml文件赢如何写呢?我们可以拿一个例子来解释:
1. 前提:
我们首先定义了java Bean:Color类
public class Color {
private Integer id;
private String name;
private Integer parentId;
private String imgUrl;
Color类对应的MySQL中的color表的字段一一对应,color表定义如下:
id,name,parent_id,img_url
2. xml文件应如何写?
首先我们看到java Bean与数据库表中的字段是对应不上的,所以,在color.xml中我们首先应该使两者对应起来
方法:使用<resultMap id="" type=""> </resultMap>映射两者关系
<mapper namespace="cn.hdu.li.core.dao.product.ColorDao">
<!-- 定义resultMap
type:ResultMap最终映射的java对象类型,可以使用别名
id:resultMap的唯一标识
-->
<resultMap id="color" type="Color">
<!-- property:类属性 column:字段名 -->
<result property="id" column="id" />
<result property="name" column="name" />
<result property="parentId" column="parent_id" />
<result property="imgUrl" column="img_url" />
</resultMap>
那剩下的就是增删改查语句了,其中parameterType为输入参数,resultMap与resultType为返回类型
查:
<!-- 根据主键查询 -->
<select id="getColorByKey" resultMap="color" parameterType="hashMap">
SELECT id,name,parent_id,img_url FROM bbs_color
WHERE
id=#{id}
</select>
增:
<insert id="addColor" parameterType="Color">
INSERT INTO bbs_color
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="name != null">
name,
</if>
<if test="parentId != null">
parent_id,
</if>
<if test="imgUrl != null">
img_url
</if>
</trim>
VALUES
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id},
</if>
<if test="name != null">
#{name},
</if>
<if test="parentId != null">
#{parentId},
</if>
<if test="imgUrl != null">
#{imgUrl}
</if>
</trim>
</insert>
删:
<!-- 根据主键批量删除 -->
<delete id="deleteByKeys">
DELETE FROM bbs_color
WHERE
id in
<foreach collection="list" separator="," item="id" open="(" close=")">
#{id}
</foreach>
</delete>
改:
<!--修改品牌-->
<update id="updateBrandByKey" parameterType="Brand">
UPDATE bbs_brand
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="description!=null">
description=#{description},
</if>
<if test="imgUrl!=null">
img_url=#{imgUrl},
</if>
<if test="sort!=null">
sort=#{sort},
</if>
<if test="isDisplay!=null">
is_display=#{isDisplay}
</if>
</set>
<where>
id=#{id}
</where>
</update>
还有一个语句:<sql >:可被其他语句引用的可重用语句块
<!-- Select SQL -->
<sql id="colorSelector">
SELECT
<if test="fields != null">
${fields}
</if>
<if test="fields == null">
id,name,parent_id,img_url
</if>
FROM bbs_color
</sql>
引用方法: 使用<sql>段的id进行引用即可
<select id="getColorListWithPage" parameterType="ColorQuery" resultMap="color">
<include refid="colorSelector" />
<include refid="colorListWhere" />
<include refid="colorListOrder" />
<include refid="colorListLimit" />
</select>