mapper.xml文件为mapper接口类的映射文件,用来存放数据库sql操作语句
1.插入数据:
1)插入数据到已知表:
<insert id="addCategory" useGeneratedKeys="true" keyProperty="id">
INSERT INTO category (id,name,label,logo_type)
VALUES (#{id},#{name},#{label},#{logoType});
</insert>
2)插入数据到动态表:
<insert id="insertExhibitImgUrl" useGeneratedKeys="true" keyColumn="id">
INSERT INTO ${tableName} (imgurl)
VALUES (#{imgurl});
</insert>
3)注解:
2.删除数据:
1)删除某一项匹配数据:
<delete id="deleteExhibitImgUrl">
DELETE FROM ${tableName} WHERE id=#{id};
</delete>
2)删除整个表中记录:
<delete id="deleteExhibitContent">
DELETE FROM ${tableName};
</delete>
3.更新数据和表
1)根据条件更新表中某项数据:
<update id="updateBannerUrlById">
UPDATE banner
<set>
<if test="imgUrl !=null">
img_url=#{imgUrl}
</if>
</set>
WHERE banner_id=#{bannerId};
</update>
2)创建表
<update id="createExhibitImgTable" useGeneratedKeys="true" keyProperty="id">
CREATE table ${tableName}
(id int NOT NULL AUTO_INCREMENT,imgurl varchar(255),PRIMARY KEY (id));
</update>
4.查询数据
1)计数表内数据项数
<select id="count" resultType="int">
SELECT count(*) FROM banner;
</select>
2.查询符合条件的数据
<select id="getBannerById" resultMap="GetBannersMap">
SELECT <include refid="BannersQueryFields"></include>
FROM banner
WHERE banner_id=#{bannerId}
</select>
<resultMap id="GetBannersMap" type="com.example.demo.pojo.vo.BannerVO">
<id column="banner_id" property="bannerId"></id>
<result column="img_url" property="imgUrl"></result>
<result column="a_href" property="abnHref"></result>
<result column="is_use" property="isUse"></result>
<result column="need_href" property="needHref"></result>
<result column="need_imgurl" property="needImgUrl"></result>
<result column="add_datetime" property="addDatetime"></result>
</resultMap>
<sql id="BannersQueryFields">
banner_id,img_url,a_href,is_use,need_href,need_imgurl,add_datetime
</sql>
5.注解
1)${} 与#{} 两个变量修饰符使用:除了数据库、表名外都用#,表名变量要用$修饰符。
2)标签id属性值对应mapper接口方法名
3)<set></set>标签用以存放更新的内容
4)<if></if>条件语句,test传进来的的值
5)创建表时设置主键自增:(id int NOT NULL AUTO_INCREMENT,imgurl varchar(255),PRIMARY KEY (id)) ;not null 不能少,注意PRIMARY KEY(id)要放在整个的括号内,在外面会报错,AUTO_INCREMENT设置自增