Mybatis动态sql中的choose标签的使用

choose标签是按顺序判断其内部when标签中的test条件是否成立,如果有一个成立,则执行该when标签中定义的SQL语句片段,并且choose标签提前结束。当choose标签中所有when标签的test条件都不满足时,则执行otherwise中的SQL。

类似于Java中的switch语句,choose为switch,when为case,otherwise则为default。

以下是choose标签中的各个子标签和属性:

when:这是choose标签中的子标签,用于定义一个条件分支。我们可以在when标签中使用test属性来指定一个条件表达式,如果该表达式的值为真,则会执行when标签中定义的SQL语句片段。

test:这是when标签中的属性,我们可以使用test属性来定义条件表达式,用于判断条件是否满足。如果条件满足,被when标签包裹的SQL语句片段将会被执行。

otherwise:这是choose标签中的可选子标签,用于定义一个默认的条件分支。如果前面的条件都不满足,将会执行otherwise标签中定义的SQL语句片段。

在数据库中构建下述表结构:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(10) NOT NULL,
  `sex` tinyint(4) NOT NULL,
  `birthday` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

并且执行下述SQL脚本初始化数据:

insert into `user` (`id`, `user_name`, `sex`, `birthday`) values('1','张伟','1','2022-02-02');
insert into `user` (`id`, `user_name`, `sex`, `birthday`) values('2','张伟','1','2022-02-03');
insert into `user` (`id`, `user_name`, `sex`, `birthday`) values('3','胡一菲','0','2022-02-03');
insert into `user` (`id`, `user_name`, `sex`, `birthday`) values('4','陈美嘉','0','2022-02-04');
insert into `user` (`id`, `user_name`, `sex`, `birthday`) values('5','吕子乔','1','2022-02-05');

构建实体类:

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

@Data
@TableName("user")
public class User {

    @TableId(type = IdType.AUTO)
    private Integer id;

    @TableField(value = "user_name")
    private String userName;

    @TableField(value = "sex")
    private Integer sex;

    @TableField(value = "birthday")
    private Date birthday;
}

构建mapper持久化接口和mapper.xml文件:

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserMapper extends BaseMapper<User> {

    List<User> getUserList(User user);
}
<?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.example.demo.mapper.UserMapper">

    <select id="getUserList" resultType="com.example.demo.entity.User" parameterType="com.example.demo.entity.User">
        select * from user u
        <where>
            <choose>
                <when test="userName != null">
                    u.user_name = #{userName, jdbcType=VARCHAR}
                </when>
                <when test="sex != null">
                    AND u.sex = #{sex, jdbcType=INTEGER}
                </when>
                <when test="birthday != null">
                    AND u.birthday = #{birthday, jdbcType=DATE}
                </when>
                <otherwise>
                    AND u.user_name = '吕子乔'
                </otherwise>
            </choose>
        </where>
    </select>

</mapper>

例如当前以userName作为条件查询数据:

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test(){
        User user = new User();
        user.setUserName("张伟");
        List<User> userList = userMapper.getUserList(user);
        userList.forEach(System.out::println);
    }
}

执行上述代码,其执行的SQL语句为select * from user u WHERE u.user_name ='张伟';,控制台的输出结果为:

User(id=1, userName=张伟, sex=1, birthday=Wed Feb 02 00:00:00 CST 2022)
User(id=2, userName=张伟, sex=1, birthday=Thu Feb 03 00:00:00 CST 2022)

例如当前以sex作为条件查询数据:

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test(){
        User user = new User();
        user.setSex(0);
        List<User> userList = userMapper.getUserList(user);
        userList.forEach(System.out::println);
    }
}

执行上述代码,其执行的SQL语句为SELECT * FROM USER u WHERE u.sex =0;,控制台的输出结果为:

User(id=3, userName=胡一菲, sex=0, birthday=Thu Feb 03 00:00:00 CST 2022)
User(id=4, userName=陈美嘉, sex=0, birthday=Fri Feb 04 00:00:00 CST 2022)

例如当前以birthday作为条件查询数据:

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.List;

@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test(){
        Date date =DateUtil.parse("2022-02-03 08:08:08",DatePattern.NORM_DATETIME_PATTERN);
        User user = new User();
        user.setBirthday(date);
        List<User> userList = userMapper.getUserList(user);
        userList.forEach(System.out::println);
    }
}

执行上述代码,其执行的SQL语句为SELECT * FROM USER u WHERE u.birthday ='2022-02-03';,控制台的输出结果为:

User(id=2, userName=张伟, sex=1, birthday=Thu Feb 03 00:00:00 CST 2022)
User(id=3, userName=胡一菲, sex=0, birthday=Thu Feb 03 00:00:00 CST 2022)

特别说明:MyBatis处理日期有两种jdbcType,即DATE和TIMESTAMP。当我们使用java.util.Date作为实体的日期类型时,java.util.Date实际上是能够表示MYSQL的三种字段类型:date、datetime和timestamp。实际将java.util.Date当做参数传递给Mapper的时候,如果我们不指定jdbcType,那么这个日期会自动转化会MySQL的timestamp。如果指定jdbcType=DATE,那么MyBatis会将传入参数截取为yyyy-MM-dd。MyBatis在做出日期类型转换后,可以直接使用 =、>、<、>=、<=符号来进行筛选。 

例如当前不以任何字段作为条件查询数据:

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    void test(){
        User user = new User();
        List<User> userList = userMapper.getUserList(user);
        userList.forEach(System.out::println);
    }
}

执行上述代码,其执行的SQL语句为select * from user u WHERE u.user_name = '吕子乔';,控制台的输出结果为:

User(id=5, userName=吕子乔, sex=1, birthday=Sat Feb 05 00:00:00 CST 2022)
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值