Mybatis中动态sql的使用

简介: Mybatis中动态sql的使用

文章目录

动态 SQL 是 MyBatis 的强大特性之一,使用动态 SQL 并非一件易事,但借助可用于任何 SQL 映射语句中的强大的动态 SQL 语言,MyBatis 显著地提升了这一特性的易用性。Mbatis-Plus封装了一些固定的单表的查询,对于一些复杂的关联还得使用sql进行查询 。

常见的标签有以下几种:

  • if
  • choose (when, otherwise)
  • trim (where, set)
  • foreach

1. if 标签

if标签可以对进行传入的参数进行判断.

<!--定义结果集-->

   <resultMap id="baseResultMap" type="com.elite.mybatis.entity.Person">

       <result column="id" property="id"/>

       <result column="name" property="name"/>

       <result column="age" property="age"/>

       <result column="email" property="email"/>

   </resultMap>

   <!--定义sql片段-->

   <sql id="selectList">

         select id,name,age,email from person

   </sql>

   <!--if标签-->

   <select id="selectPersonByName" resultMap="baseResultMap">

         <include refid="selectList"></include>

         where 1=1

         <if test="name!=null and name!= ''">

            and  name like  CONCAT('%',CONCAT(#{name},'%'))

         </if>

   </select>

测试

public class TestDynamicSql {

   SqlSession sqlSession =null;

   @Before

   public void init() throws IOException {

       InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");

       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

       sqlSession = sqlSessionFactory.openSession();

   }

   /**

    * 查询人员信息

    */

   @Test

   public void testIf()  {

       PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

       List<Person> personList = personMapper.selectPersonByName(null);

       personList.forEach(p->{

           System.out.println(p.toString());

       });

       PersonMapper personMapper1 = sqlSession.getMapper(PersonMapper.class);

       List<Person> personList1 = personMapper.selectPersonByName("elite");

       personList1.forEach(p->{

           System.out.println(p.toString());

       });

   }

}

2.choose、when、otherwise

choose可以根据条件进行判断加上条件进行查询。

/**

    * selectPersonByNameAndAge

    */

   /**

    * 查询人员信息

    */

   @Test

   public void testChoose() {

       PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

       System.out.println("================传入名字按名字查询===============================");

       List<Person> personList = personMapper.selectPersonByNameAndAge("elite",null);

       personList.forEach(p -> {

           System.out.println(p.toString());

       });

       System.out.println("==================传入年龄按年龄查询=============================");

       List<Person> personList1 = personMapper.selectPersonByNameAndAge(null,24);

       personList1.forEach(p -> {

           System.out.println(p.toString());

       });

       System.out.println("===============都不传入按默认的id=1查询返回================================");

       List<Person> personList2 = personMapper.selectPersonByNameAndAge(null,null);

       personList2.forEach(p -> {

           System.out.println(p.toString());

       });

   }

3a9cc451a7124bdbb02e7a250401f13a.png

3. trim、where、set

前边拼接sql的地方可能一个条件都不加的情况下,我们需要写一个where 1=1才可以,这几个标签就可以解决这个问题。

   <select id="selectPersonById" resultMap="baseResultMap">

       <include refid="selectList"></include>

       <where>

           <if test="id != null and id!= '' ">

               id = #{id}

           </if>

       </where>

   </select>

测试代码

  /**

    * 查询人员信息

    */

   @Test

   public void testWhere() {

       PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

       System.out.println("================不传入id===============================");

       List<Person> personList = personMapper.selectPersonById(null);

       personList.forEach(p -> {

           System.out.println(p.toString());

       });

       System.out.println("================传入id===============================");

       List<Person> personList1 = personMapper.selectPersonById(1L);

       personList1.forEach(p -> {

           System.out.println(p.toString());

       });

   }

测试set

<!--set标签-->

   <update id="updatePersonById">

       update person

       <set>

           <if test="name != null">name=#{name},</if>

           <if test="age != null">age=#{age},</if>

           <if test="email != null">email=#{email}</if>

       </set>

       where id=#{id}

   </update>

测试

/**

    * 测试更新

    */

   @Test

   public void testSet() {

       PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

       Person p = new Person();

       p.setId(1L);

       p.setName("testset");

       p.setEmail("testset@qq.com");

       personMapper.updatePersonById(p);

       System.out.println(personMapper.selectPerson(1L).toString());

       //Person{id=1, name='testset', age=22, email='testset@qq.com'}

   }

4. foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历。

mapperxml

 

<!--foreach-->

   <select id="selectPersonByIds" resultMap="baseResultMap">

       <include refid="selectList"></include>

       <where>

           <foreach item="item" index="index" collection="ids"

                    open="id in (" separator="," close=")">

               #{item}

           </foreach>

       </where>

   </select>

测试

/**

    * 测试更新

    */

   @Test

   public void testForeach() {

       PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

       Long[] ids = new Long[]{1L,2L};

       personMapper.selectPersonByIds(ids).forEach(person -> {

           System.out.println(person.toString());

       });

   }

测试结果

Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@12b08d6]

==>  Preparing: select id,name,age,email from person WHERE id in ( ? , ? )

==> Parameters: 1(Long), 2(Long)

<==    Columns: id, name, age, email

<==        Row: 1, elite, 22, elite@qq.com

<==        Row: 2, elite2, 24, elite2@qq.com

<==      Total: 2

Person{id=1, name='elite', age=22, email='elite@qq.com'}

Person{id=2, name='elite2', age=24, email='elite2@qq.com'}



相关文章
|
6月前
|
SQL Java 测试技术
3、Mybatis-Plus 自定义sql语句
这篇文章介绍了如何在Mybatis-Plus框架中使用自定义SQL语句进行数据库操作。内容包括文档结构、编写mapper文件、mapper.xml文件的解释说明、在mapper接口中定义方法、在mapper.xml文件中实现接口方法的SQL语句,以及如何在单元测试中测试自定义的SQL语句,并展示了测试结果。
3、Mybatis-Plus 自定义sql语句
|
29天前
|
SQL Java 数据库连接
【潜意识Java】MyBatis中的动态SQL灵活、高效的数据库查询以及深度总结
本文详细介绍了MyBatis中的动态SQL功能,涵盖其背景、应用场景及实现方式。
96 6
|
2月前
|
SQL XML Java
mybatis实现动态sql
MyBatis的动态SQL功能为开发人员提供了强大的工具来应对复杂的查询需求。通过使用 `<if>`、`<choose>`、`<foreach>`等标签,可以根据不同的条件动态生成SQL语句,从而提高代码的灵活性和可维护性。本文详细介绍了动态SQL的基本用法和实际应用示例,希望对您在实际项目中使用MyBatis有所帮助。
102 11
|
3月前
|
SQL 缓存 Java
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
本文详细介绍了MyBatis的各种常见用法MyBatis多级缓存、逆向工程、分页插件 包括获取参数值和结果的各种情况、自定义映射resultMap、动态SQL
【详细实用のMyBatis教程】获取参数值和结果的各种情况、自定义映射、动态SQL、多级缓存、逆向工程、分页插件
|
3月前
|
SQL Java 数据库连接
canal-starter 监听解析 storeValue 不一样,同样的sql 一个在mybatis执行 一个在数据库操作,导致解析不出正确对象
canal-starter 监听解析 storeValue 不一样,同样的sql 一个在mybatis执行 一个在数据库操作,导致解析不出正确对象
|
4月前
|
SQL Java 数据库连接
mybatis使用四:dao接口参数与mapper 接口中SQL的对应和对应方式的总结,MyBatis的parameterType传入参数类型
这篇文章是关于MyBatis中DAO接口参数与Mapper接口中SQL的对应关系,以及如何使用parameterType传入参数类型的详细总结。
86 10
|
5月前
|
SQL XML Java
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
文章介绍了MyBatis中动态SQL的用法,包括if、choose、where、set和trim标签,以及foreach标签的详细使用。通过实际代码示例,展示了如何根据条件动态构建查询、更新和批量插入操作的SQL语句。
mybatis复习03,动态SQL,if,choose,where,set,trim标签及foreach标签的用法
|
6月前
|
SQL Java 数据库连接
Mybatis系列之 Error parsing SQL Mapper Configuration. Could not find resource com/zyz/mybatis/mapper/
文章讲述了在使用Mybatis时遇到的资源文件找不到的问题,并提供了通过修改Maven配置来解决资源文件编译到target目录下的方法。
Mybatis系列之 Error parsing SQL Mapper Configuration. Could not find resource com/zyz/mybatis/mapper/
|
5月前
|
SQL XML Java
mybatis :sqlmapconfig.xml配置 ++++Mapper XML 文件(sql/insert/delete/update/select)(增删改查)用法
当然,这些仅是MyBatis功能的初步介绍。MyBatis还提供了高级特性,如动态SQL、类型处理器、插件等,可以进一步提供对数据库交互的强大支持和灵活性。希望上述内容对您理解MyBatis的基本操作有所帮助。在实际使用中,您可能还需要根据具体的业务要求调整和优化SQL语句和配置。
95 1
|
6月前
|
SQL Java 数据库连接
Mybatis系列之 动态SQL
文章详细介绍了Mybatis中的动态SQL用法,包括`<if>`、`<choose>`、`<when>`、`<otherwise>`、`<trim>`和`<foreach>`等元素的应用,并通过实际代码示例展示了如何根据不同条件动态生成SQL语句。