Java - MyBatis中的动态SQL是什么意思?
2017-11-08 10:03
471 查看
对于一些复杂的查询,我们可能会指定多个查询条件,但是这些条件可能存在也可能不存在,例如在58同城上面找房子,我们可能会指定面积、楼层和所在位置来查找房源,也可能会指定面积、价格、户型和所在位置来查找房源,此时就需要根据用户指定的条件动态生成SQL语句。如果不使用持久层框架我们可能需要自己拼装SQL语句,还好MyBatis提供了动态SQL的功能来解决这个问题。MyBatis中用于实现动态SQL的元素主要有:
- if
- choose / when / otherwise
- trim
- where
- set
- foreach
下面是映射文件的片段。
当然也可以像下面这些书写。
- if
- choose / when / otherwise
- trim
- where
- set
- foreach
下面是映射文件的片段。
<select id="foo" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <if test="title != null"> and title = #{title} </if> <if test="content != null"> and content = #{content} </if> <if test="owner != null"> and owner = #{owner} </if> </select>
当然也可以像下面这些书写。
<select id="foo" parameterType="Blog" resultType="Blog"> select * from t_blog where 1 = 1 <choose> <when test="title != null"> and title = #{title} </when> <when test="content != null"> and content = #{content} </when> <otherwise> and owner = "owner1" </otherwise> </choose> </select>再看看下面这个例子。
<select id="bar" resultType="Blog"> select * from t_blog where id in <foreach collection="array" index="index" item="item" open="(" separator="," close=")"> #{item} </foreach> </select>
相关文章推荐
- mybatis动态sql根据java枚举判断不执行,执行otherwise,解决办法
- JAVAWEB开发之mybatis详解(一)——mybatis的入门(实现增删改查操作)、自定义别名、抽取代码块以及动态SQL的使用
- Java数据持久层框架 MyBatis之API学习七(动态 SQL详解)
- java框架之Mybatis04(动态SQL)
- Java的MyBatis框架中对数据库进行动态SQL查询的教程
- JAVA mybatis:mapper 中的动态SQL
- java mybatis 之 mysqlmap 动态 sql 语句
- java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE是什么意思
- 告诉你什么是MyBatis的动态 SQL···
- 【JAVA - SSM】之MyBatis动态SQL
- 【JAVA - SSM】之MyBatis动态SQL
- java mybatis 动态sql
- Java学习笔记33:mybatis动态SQL语句
- mybatis使用动态sql时报错:There is no getter for property named '*' in 'class java.lang.String
- 详解Java的MyBatis框架中动态SQL的基本用法
- mybatis 动态sql语句(1)
- MyBatis中动态SQL
- MyBatis_7 - MyBatis动态SQL
- MyBatis的动态SQL操作
- MyBatis--动态SQL原笔记(无案例)