mybatis 查询 动态sql语句怎么写

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis 查询 动态sql语句怎么写相关的知识,希望对你有一定的参考价值。

参考技术A mybatis的sql和你在数据库客户端执行的sql是一样的,但是在mybatis中调用的sql一般都是动态的,所以用到了参数传递。这个mybatis有对应的标签以及相应的变量来实现。你可以搜索下mybatis标签。同时给你一个参考的你看看,这个是一个查询用户的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

<select id="queryUsers" parameterType="map" resultType="xx.xx.xx.bean.UserBean">
<![CDATA[
select
ID,
LOGIN_NAME AS loginName,
PASSWORD,
REAL_NAME AS realName,
POSITION,
(SELECT D.POSITION_NAME FROM UNIT_POSITION D WHERE D.POSITION_CODE=T.POSITION) POSITIONNAME,
USER_TYPE AS userType,
SEX,
PID,
TO_CHAR(T.BIRTHDAY,'YYYY-MM-DD') BIRTHDAY,
EMAIL,
CONTACT_TEL AS contactTel,
CONTACT_MOBILE AS contactMobile,
CONTACT_FAX AS contactFax,
CONTACT_ZIP AS contactZip,
CONTACT_ADDR AS contactAddr,
STATUS,
EDUCATION,
(SELECT D.EDUCATION_NAME FROM UNIT_EDUCATION D WHERE D.EDUCATION_CODE=T.EDUCATION AND D.STATUS=0) EDUCATIONNAME,
NATION,
POLITICAL,
REMARK,
TO_CHAR(T.CREATE_DATE,'YYYY-MM-DD HH24:MI:SS') createDate,
(SELECT D.REAL_NAME FROM UNIT_USER D WHERE D.ID= T.CREATE_USER_ID) createUserId,
TO_CHAR(T.UPDATE_DATE,'YYYY-MM-DD HH24:MI:SS') updateDate,
(SELECT D.REAL_NAME FROM UNIT_USER D WHERE D.ID= T.UPDATE_USER_ID) updateUserId
from UNIT_USER T
]]>
<where>
T.STATUS='1'
<if test="realName !=null and realName !=''">
and T.REAL_NAME like '%$realName%'
</if>
<if test="nexusDpartment !=null">
AND T.ID IN (SELECT DISTINCT D.USER_ID FROM UNIT_USER_DEPT D WHERE D.DEPT_CODE IN ($nexusDpartment))
</if>
<if test="deptCode !=null and deptCode !=''">
AND T.ID IN (SELECT DISTINCT D.USER_ID FROM UNIT_USER_DEPT D WHERE D.DEPT_CODE = #deptCode)
</if>
</where>
<if test="sort != null and sort != ''">
order by $sort
<if test="direction != null and direction != ''">
$direction
</if>
</if>
</select>本回答被提问者采纳

Mybatis动态SQL语句使用

在实际开发中,有时候查询条件可能是不确定的,查询条件可能有多条也可能没有,这时候就需要用到动态的sql语句拼接功能。

 

一、ifwheresql标签的使用

需求:在一些高级查询中,查询条件存在的个数不确定。如,SELECT * FROM user WHERE username LIKE ‘%明%‘ AND sex = ‘1‘;

为了能够动态拼接sql语句可以采用以下方式:

UserMapper.xml

<select id="findUserByUserNameAndSex" parameterType="cn.itheima.pojo.User" resultType="cn.itheima.pojo.User">
   SELECT * FROM user <!-- where标签作用: 会自动向sql语句中添加where关键字 会去掉第一个条件的and语句 --> <where> <if test="username != null and username != ‘‘">    AND username LIKE ‘%${username}%‘   </if> <if test="sex != null and sex != ‘‘">   AND sex=#{sex} </if> </where> </select>

where标签下的查询条件放在findUserByUserNameAndSex中,只能在该范围内使用。为了实现代码的重用性,通常将查询条件放在外面,由不同的查询共同调用。

  <sql id="user_where">
       <where>
           <if test="username != null and username != ‘‘">
              AND username LIKE ‘%${username}%‘
          </if>
            <if test="sex != null and sex != ‘‘">
            AND sex=#{sex}
            </if>
        </where>
    </sql>
<select id="findUserByUserNameAndSex" parameterType="cn.itheima.pojo.User" resultType="cn.itheima.pojo.User"> SELECT * FROM user <!-- 调用sql条件 --> <include refid="user_where"></include> </select>    

UserMapper.java中编写接口

List<User> findUserByUserNameAndSex(User user);

测试

    @Test
    public void testFindUserByUserNameAndSex() throws Exception {
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = new User();
        user.setUsername("明");
        user.setSex("1");
        List<User> userList = userMapper.findUserByUserNameAndSex(user);
        System.out.println(userList);
    }

 

 

二、foreach标签的使用

需求:SQL语句中,SELECT * FROM user WHERE id IN (1,15,22,28);为了从service层接收多个id值,然后使用foreach标签动态拼接多个id值组成完整的SQL语句。

UserMapper.xml

 

    <select id="findUserByIds" parameterType="cn.itheima.pojo.QueryVO" resultType="cn.itheima.pojo.User">
        SELECT * FROM user
        <where>
            <if test="ids != null">
                <!--
                foreach:循环传入的集合参数
                collection:传入的集合的变量名称
                item:每次循环将循环出的数据放入这个变量
                open:循环开始拼接的字符串
                close:循环结束拼接的字符串
                separator:循环中拼接的分隔符
                 -->
                <foreach collection="ids" item="id" open=" id IN (" close=")" separator=",">
                    #{id}
                </foreach>
            </if>
        </where>
    </select>

 QueryVO.java

package cn.itheima.pojo;

import java.util.List;

public class QueryVO {
    private List<Integer> ids;
    public List<Integer> getIds() {
        return ids;
    }
    public void setIds(List<Integer> ids) {
        this.ids = ids;
    }
}

多个id值可以通过QueryVO类传递给DAO层。

UserMapper.java接口中编写接口

List<User> findUserByIds(QueryVO vo);

测试

    @Test
    public void testFindUserByIds() throws Exception {
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper = session.getMapper(UserMapper.class);
        QueryVO vo = new QueryVO();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(15);
        ids.add(22);
        ids.add(28);
        vo.setIds(ids);
        List<User> userList = userMapper.findUserByIds(vo);
        System.out.println(userList);
    }

 



以上是关于mybatis 查询 动态sql语句怎么写的主要内容,如果未能解决你的问题,请参考以下文章

mybatis 动态sql语句怎么写if else

Oracle -Mybatis动态SQL查询分页的实现

动态sql

MyBatis:动态SQL

mybatis 详解------动态SQL

Mybatis动态查询语句