我们在使用了mybatis框架后,向数据库发送SQL语句就需要编写在dao接口同名的xml文件中。在其中我们会使用到<select>,<insert>,<update>等标签来装载SQL语句,例如查询语句如下:
<!-- 查询用户by ID -->
<select id="findUserById" parameterType="Integer" resultType="userPo">
SELECT * FROM USER WHERE userid = #{UserID}
</select>
属性id的值必须与dao接口中对应的方法一致,parameterType属性声明了SQL的参数类型,resultType属性声明SQL的返回值类型,它们的值可以是String、Integer这样的包装类,也可以是ProductPo这种bean对象。与传统SQL语句参数不同,在mybatis中使用#{参数名}来传递参数。如果参数是字符串类型的数据,需要使用引号包裹,可以直接使用+来进行拼接,如:
<!-- 查询用户by number -->
<select id="findUserByNumber" parameterType="String" resultType="userPo">
SELECT * FROM USER WHERE usernumber like "'" + #{Number} + "'"
</select>
但是一般都不推荐这种写法,因为这样很容易造成SQL注入,使代码安全性下降,推荐使用concat函数,如:
<!-- 查询用户by number -->
<select id="findUserByNumber" parameterType="String" resultType="userPo">
SELECT * FROM USER WHERE usernumber like concat("'",#{Number},"'")
</select>
有时候查询语句的条件可能不止一个,那么parameterType属性就可以不写,但是在dao接口中的方法需要添加@Param注解,来指明参数。
public List<ExamplePo> findAllExample(@Param("startIndex") int startIndex,
@Param("limit") int limit,@Param("exampletitle") String exampletitle);
需要注意的是,@Param中的值必须与#{}中的一致,否则程序会报错。这样肯定会觉得特别的繁琐,如果参数过多,可以将其封装为一个bean对象,已bean的形式来接收和传递参数
//Condition 所有查询条件参数的POJO对象
public List<BusinessPo> findInfo(Condition condition);
insert、update和delete标签没有resultType属性,它默认返回数据库数据变更数,为Integer类型。
<!-- 新增产品 -->
<insert id="addProduct" parameterType="productPo">
INSERT INTO product(productname,productdescribe,cover)
VALUES(#{productname},#{productdescribe},#{cover})
</insert>
如果有一段SQL语句在多个方法中都会使用到,那么我们可以使用<sql>标签将其包裹起来,如:
<!-- 查询套餐信息SQL -->
<sql id="findSetMeal">
select * from B_Setmeal inner join B_SetmealType
on B_Setmeal.SetmealTypeID = B_SetmealType.SetmealTypeID
</sql>
之后在其他方法中,使用<include>标签,通过属性id的值对其进行引用。
<!-- 查询套餐信息ByID -->
<select id="findById" resultType="SetMealPo">
<include refid="findSetMeal"/>
<where>
B_Setmeal.SetmealID = #{id}
</where>
</select>
<!-- 查询套餐列表by类型ID -->
<select id="findAll" resultType="SetMealPo">
<include refid="findSetMeal"/>
<where>
B_Setmeal.SetmealTypeID = #{id}
</where>
</select>
有时候我们需要在SQL语句中加入【<】或者【>】,这个时候由于这两个符号会被识别为标签括号,造成报错。
<!-- 查询表格数据 -->
<select id="findInfo" resultType="BusinessPo" parameterType="Condition">
select * from (<include refid="innerjoin"/>) as e
<where>
<if test="StartDate !=null and StartDate !=''">
<!-- 时间比较时用到了<= 虽然现在没有提示出错 但是SQL运行时会无法识别 -->
and SaveDate <= #{StartDate}
</if>
order by e.SaveDate desc
</where>
</select>
在需要使用到某些特殊符号的时候,可以使用其对应的编码来表示,如:<(<)、>(>)
<if test="StartDate !=null and StartDate !=''">
and SaveDate <= #{StartDate}
</if>
<if test="EndDate !=null and EndDate !=''">
and SaveDate >= #{EndDate}
</if>
本文详细介绍了MyBatis框架下如何使用SQL映射,包括<select>、<insert>、<update>等标签的应用,以及如何处理SQL参数、避免SQL注入和复用SQL片段。
74





