MyBatis(三) ——动态sql和多表联查

一、动态sql

动态sql是,根据数据的变化,sql语句也做出相应的变化,例如,在搜索时,根据输入的值的不同,来改变sql语句的查询条件,最后查出来不同的数据。

name!=null address
select * from 表名 where name=#{name} and address=#{address}
name==null
select * from 表名.

mybatis中的动态sql标签

1.1 if标签——单条件判断

语法:

<if test="条件">

要执行的sql语句

</if>

     <select id="findByCondition" resultType="com.ykq.entity.Account">
        select * from account where 1=1
        <if test="name!=null and name!=''">
             and  name=#{name}
        </if>
        <if test="money!=null">
             and  money=#{money}
        </if>
    </select>

1.2 choose标签——多条件分支判断

choose类似于Java中的switch条件判断 。用于动态sql的多条件判断,otherwise时当条件都不满足时执行的语句。

<select id="findByCondition02" resultType="com.ykq.entity.Account">
        select * from account where 1=1
        <choose>
             <when test="name!=null and name!=''">
                 and  name=#{name}
             </when>
            <when test="money!=null">
                and  money=#{money}
            </when>
            <otherwise>
                and isdeleted=0
            </otherwise>
        </choose>
    </select>

1.3 where标签

        我们观察到上面的sql都加了 where 1=1 ,如果不使用where 1=1 那么你的动态sql可能会出错。 我们能不能不加where 1=1呢! 可以 那么我们就可以使用where标签。

        作用:可以自动为你添加where关键字,并且可以帮你去除第一个and 或是 or

上面的语句就可以修改为:

<select id="findByCondition" resultType="com.ykq.entity.Account">
        select * from account
        <where>
            <if test="name!=null and name!=''">
                 and  name=#{name}
            </if>
            <if test="money!=null">
                 and  money=#{money}
            </if>
        </where>
    </select>

1.4 set标签

        这个配合if标签一起用,一般用在修改语句。如果传递的参数值为null,那么应该不修改该列的值。

        作用:可以帮我们生成关键字 set 并且可以去除最后一个逗号


    <update id="update">
          update account
          <set>
             <if test="name!=null and name!=''">
                name=#{name},
             </if>
             <if test="money!=null">
                money=#{money},
             </if>
             <if test="isdeleted!=null">
                 isdeleted=#{isdeleted},
             </if>
             <if test="created!=null">
                  created=#{created},
             </if>
             <if test="updated!=null">
                  updated=#{updated},
             </if>
          </set>
          where id=#{id}
    </update>

1.5 foreach标签——循环

在foreach标签中:

        collection:类型,如果你传入的参数是数组,就用array,是集合就用list
        item:数组中每个元素赋值的变量名
        open: 以谁开始
        close:以谁结束
        separator:分割符

    <!-- select * from account where id in(2,3,5,7,0)
        如果你使用的为数组array  如果你使用的为集合 那么就用list
        collection:类型
        item:数组中每个元素赋值的变量名
        open: 以谁开始
        close:以谁结束
        separator:分割符
    -->
    <!--一次查询多个-->
    <select id="findByIds" resultType="com.xrx.entity.Account">
        select * from account where id in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
             #{id}
        </foreach>
    </select>


    <!--一次删除多个-->
     <delete id="batchDelete">
        <foreach collection="array" item="id" open="delete from account where  id in("             close=")" separator=",">
            #{id}
        </foreach>
    </delete>

    <!--一次添加多个-->
    <insert id="saveBatch">
        insert into account(name,isdeleted) values
        <foreach collection="list" item="acc" separator=",">
            (#{acc.name},#{acc.isdeleted})
        </foreach>
    </insert>

1.6 sql标签

        在执行sql语句是,建议是将要操作的字段写出来,不建议使用 * 代替,为了字段可重复使用,就要用到sql标签。

定义时使用<sql id=""></sql>,在使用时要用到<include refid="id名"><include/>

    <sql id="tb_emp">
        e.id,e.name,age,job,salary,entrydate,dept_id,d.id did,d.name dname,address
    </sql>
    <select id="findById" resultType="com.xrx.entity.Emp">
        select <include refid="tb_emp"></include> from tb_emp e where id in
        <foreach collection="array" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </select>

二、特殊字符处理和模糊查询

2.1 特殊字符处理

        在sql中我们会使用到一些特殊的字符,例如>,<,%等,我们直接写在sql中时,会被识别错误,导致sql不能完成本来的功能。特殊字符的处理有两种方法:

       第一种:转义标签 &nbsp; &lt;  
       第二种: <![CDATA[sql]]>

    <select id="findByMaxMin" resultType="com.xrx.entity.Account">
           <![CDATA[select * from account where id >#{min} and id <#{max}]]>
    </select>

2.2 模糊查询

第一中方法:使用字符串函数 完成拼接 sql

    <select id="findByLike" resultType="com.xrx.entity.Account">
        select * from account where name like concat('%',#{name},'%')
    </select>

第二种方法:使用${}

    <select id="findByLike" resultType="com.xrx.entity.Account">
        select * from account where name like '%${name}%'
    </select>

        使用${}实际上是字符串拼接,它的缺点就是不能防止sql注入, 而#{}它是预编译,它可以防止sql注入问题。

三、联表查询

根据外键来查询出来两个表中的数据,利用多的一方来查询一的一方。

3.1 创建实体类

//员工表 
public class Emp {
    private  Integer id;
    private String name;
    private Integer age;
    private String job;
    private Integer salary;
    private Date entrydate;
    private Integer deptId;
    private Dept dept;
}

//部门表
public class Dept {
    private Integer id;
    private String name;
    private String address;
}

3.2 编写xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.xrx.dao.EmpDao">
    <resultMap id="emp" type="com.xrx.entity.Emp">
        <id column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="job" property="job"/>
        <result column="salary" property="salary"/>
        <result column="entrydate" property="entrydate"/>
        <result column="dept_id" property="deptId"/>
        <association property="dept" javaType="com.xrx.entity.Dept">
            <id column="did" property="id"/>
            <result column="dname" property="name"/>
            <result column="address" property="address"/>
        </association>
    </resultMap>
    <sql id="tb_emp">
        e.id,e.name,age,job,salary,entrydate,dept_id,d.id did,d.name dname,address
    </sql>
    <select id="find" resultMap="emp">
        select <include refid="tb_emp"></include> from
         tb_emp e join tb_dept d on e.dept_id = d.id where e.id=#{id}
    </select>
</mapper>

3.3 测试

@Test
    public void find() throws Exception{
        SqlSession session = getsession();
        EmpDao empDao = session.getMapper(EmpDao.class);
        Emp emp = empDao.find(1);
        System.out.println(emp);
        session.commit();
        session.close();
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis动态注解的多表联查可以通过使用@Results和@Many注解来实现。首先,在Dao接口的方法上使用@Select注解来执行查询操作,并在@Results注解中定义结果集的映射关系。对于一对多的关系,可以使用@Many注解来指定关联的查询方法。例如,可以在UserDao接口中定义一个findAllUser方法,使用@Select注解查询User表的数据,并在@Results注解中使用@Many注解来查询关联的Account表的数据。具体的代码示例如下: ```java public interface UserDao { @Select("select * from user") @Results(id = "userMap", value = { @Result(id = true, column = "id", property = "id"), @Result(column = "username", property = "username"), @Result(column = "password", property = "password"), @Result(column = "address", property = "address"), @Result(property = "accounts", column = "id", many = @Many(select = "mediacomm.dao.AccountDao.findAccountByUid")) }) List<User> findAllUser(); } public interface AccountDao { @Select("select * from account where uid=#{uid}") List<Account> findAccountByUid(int uid); } ``` 在上述代码中,findAllUser方法使用@Results注解定义了结果集的映射关系,其中使用@Many注解来查询关联的Account表的数据。AccountDao接口中的findAccountByUid方法用于查询Account表的数据。 通过以上的配置,可以实现MyBatis动态注解的多表联查。 #### 引用[.reference_title] - *1* *2* *3* [MyBatis通过注解实现多表联查:一对一/多对一关系](https://blog.csdn.net/weixin_42717117/article/details/118763110)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值