mybatis的mapper.xml中sql的用法

刚接触的时候会有些摸不到头脑,为此在网上搜索了一些相关的参考给自己作为借鉴
1.根据id查询

select * from test_tb_info where 1=1 
<if test="id != null and id !=''">
and info.id=#{id}
</if>
<if test="....">
.......
</if> 
</select>
<resultMap type="com.....test.testFileBean" id="testFileBean">
<id column="id" property="id" />  //主键与其他字段有区别,需要注意
<result column="age" property="age"/>    //column表示字段在数据库中对应的名称,property表示在实体bean中对应的名称
<result column="name" property="name" />
<result column="path" property="path" />
</resultMap>
parameterType表示给sql语句传入的参数的类型,如上java.lang.String;
resultMap表示返回的类型是一个map集合,如上testFileBean,testFileBean是一个引用类型,表示的是上面id为testFileBean的
resultMap片段。id是作为标记使用,确保sql语句在mapper.xml中的唯一性。 if是用来对其内部字段id进行判断,test属性表示判
断的条件。

2.根据id删除文件

<delete id="delete" parameterType="java.lang.String" >
delete from tb_test where id = #{delId}
</delete>
#{delId}表示的是我们的传入的id属性的名称,必须与实体bean中的命名相同。删除没有返回,所以我们只需要写输入类型。
  1. 添加
<insert id="insert" parameterType="TestInfoBean">
	 isnert into test_info(id,name)
	 values
	 (#{id},#{name})
	</insert>

4.修改

<update id="update" parameterType="TestInfoBean">
	    update test_info set id=#{id},name=#{name} where id=#{id}   //和我们写sql语句一样,只是把参数值换为#{...}变量
</update>

也可以这样写:
<update id="update" parameterType="TestInfoBean">
    update test_info 
	 <set> id=#{id},name=#{name} </set>       //使用set标签
    where id=#{id}  
</update

5.<动态sql片段的使用

<sql id="select_test">    
	<if test="id != null"> and id=#{id}</if>
	<if test="name != null and name.length()>0"> and name=#{name}</if>
	<if test="age != null and age.length()>0"> and age=#{age}</if>    
</sql>

原作者:zhb_Simple
来源:CSDN
原文:https://blog.csdn.net/zhb_simple/article/details/78678534

猜你喜欢

转载自blog.csdn.net/weixin_43925626/article/details/84940475