一.mapper代理开发的原则
要求mapper映射文件中的namespace属性值,必须是mapper代理接口的全限定名称
要求mapper映射文件中,sql语句标签的声明,与mapper接口方法的声明一致(方法用同一个名字)
要求sql语句的resultType属性指定的类型(如果返回值是一个集合,resultType指定的是集合中存放的类型),与mapper接口方法的返回值类型一致
要求sql语句的id属性值,与mapper接口的方法名称一致
要求sql语句的parameterType属性指定的类型,与mapper接口方法的参数类型一致
1.增加操作
<insert id="insertUser" parameterType="com.code.po.User">
insert into `user`(id,username,birthday,sex,address)
values(#{id},#{username},#{birthday},#{sex},#{address})//这里的属性要和前面的对应
</insert>
2.获取数据库维护的主键值(只能在刚插入时获取)
<!--BEFORE?oracle数据库使用-->
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="BEFORE">
select seq.nextval from dual
</selectKey>
<!--after?oracle数据库使用-->
<selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
select LAST_INSERT_ID()
</selectKey>
3.根据id修改数据
<update id="updateUserById" parameterType="com.code..po.User">
update `user`
set username=#{username},sex=#{sex} where id=#{id}
</update>
4.根据id删除数据
<delete id="deleteUserById" parameterType="int">
delete from `user` where id=#{id}
</delete>
二:动态的sql(if、where、sql(include)、foreach、set)
2.1.在固定的语句写法下,如果有条件没有传递,mybatis框架会默认设置null值,导致查不到数据
2.1.1.if标签
<select id="queryUserByNameAndSex" parameterType="user" resultType="User">
select * from `user`
where <!-- username like #{username} and sex=#{sex} -->
<!-- if标签:判断用户名称不为空,且不为空字符串,才作为条件 -->
<if test="username !=null and username !=''">
username like #{username}
</if>
<!-- if标签:判断用户性别不为空,且不为空字符串,才作为条件 -->
<if test="sex !=null and sex !=''">
and sex=#{sex}
</if>
</select>
2.1.2.where标签
相当于sql语句中的where关键字根据传入的参数情况
智能的去掉多余的and、or关键字根据传入的参数情况
智能的去掉多余的where关键字
<select id="queryUserByNameAndSex" parameterType="user" resultType="User">
select * from `user`
<!-- where --> <!-- username like #{username} and sex=#{sex} -->
<where>
<!-- if标签:判断用户名称不为空,且不为空字符串,才作为条件 -->
<if test="username !=null and username !=''">
username like #{username}
</if>
<!-- if标签:判断用户性别不为空,且不为空字符串,才作为条件 -->
<if test="sex !=null and sex !=''">
and sex=#{sex}
</if>
</where>
</select>
2.1.3.where标签
<update id="dynamicUpdateUser" parameterType="user">
update `user`
<!-- set --> <!-- username='小李6号',sex='2' where id=2 -->
<set>
<if test=" username!= null and username !=''">
username=#{username},
</if>
<if test="sex != null and sex !=''">
sex=#{sex},
</if>
</set>
<where>
id=#{id}
</where>
</update>
2.1.4.where标签
<insert id="batchInsertUser" parameterType="list">
insert into `user`(username,birthday,sex,address)
values
<!--foreach:循环处理参数集合
collection:参数集合,这里是list
item:当前循环的对象引用
separator:指定分割符
open:拼装的sql片段的开始部分
close:拼装的sql片段的结束部分
-->
<foreach collection="list" item="u" separator=",">
(#{u.username},#{u.birthday},#{u.sex},#{u.address})
</foreach>
<!-- ('用户1','2018-05-29','1','地址1'),('用户2','2018-05-29','1','地址2') -->
</insert>
2.1.5.sql标签