幽兰生空谷
--绝世独自开

Mybatis快速入门(七)-动态SQL

动态SQL

精确查询:

引入 log4j.properties 文件,放到 resource 目录下

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=d:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

这里使用代理开发方式,创建dao层

package com.itheibai.dao;
import com.itheibai.entity.User;
import java.util.List;

public interface UserDao {
    List<User> findByCondition1(User user);
}

创建mapper文件

<?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.itheibai.dao.UserDao">
    <!--精确条件查询-->
    <select id="findByCondition1" parameterType="user" resultType="user">
        select * from user where id=#{id} and username=#{username} and password=#{password}
    </select>
</mapper>

创建测试类

package com.itheibai.test;
import com.itheibai.dao.UserDao;
import com.itheibai.entity.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyBatisTest {
    @Test
    public void test1() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //模拟传入的user条件数据
        User condition = new User();
        condition.setId(1);
        condition.setUsername("张三");
        condition.setPassword("123456");
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        List<User> userList = userDao.findByCondition1(condition);
        System.out.println(userList);
        sqlSession.close();
    }
}

精确查询结果

<if>条件查询

方式一:

<!--if条件查询方式一-->
<select id="findByCondition2" parameterType="user" resultType="user">
    select * from user where 1=1
    <if test="id!=0">
        and id=#{id}
    </if>
    <if test="username!=null">
        and username=#{username}
    </if>
    <if test="password!=null">
        and password=#{password}
    </if>
</select>

测试:

@Test
public void test2() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //模拟传入的user数据
    User condition = new User();
    condition.setId(1);
    condition.setUsername("张三");
    //这里没传password
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    List<User> userList = userDao.findByCondition2(condition);
    System.out.println(userList);
    sqlSession.close();
}

查询结果:

查询语句后面 没有出现 password

方式二:

<!--if条件查询方式二,where标签相当于where 1=1-->
<select id="findByCondition3" parameterType="user" resultType="user">
    select * from user
    <where>
        <if test="id!=0">
            and id=#{id}
        </if>
        <if test="username!=null">
            and username=#{username}
        </if>
        <if test="password!=null">
            and password=#{password}
        </if>
    </where>
</select>

<foreach>标签

循环执行 sql 的拼接操作,例如:

select * from user where id in (1,2,5)

查询语句

<!--foreach标签拼接-->
<select id="findByCondition4" parameterType="list" resultType="user">
    select * from user 
    <where>
        <foreach collection="list" open="id in(" close=")" item="id" separator=",">
            #{id}
        </foreach>
    </where>
</select>

在dao层添加方法

package com.itheibai.dao;
import com.itheibai.entity.User;
import java.util.List;
public interface UserDao {
    List<User> findByCondition1(User user);
    List<User> findByCondition2(User user);
    List<User> findByCondition3(User user);
    List<User> findByCondition4(List<Integer> list);
}

测试代码

@Test
public void test4() throws IOException {
    InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //模拟传入的list数据
    List<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    UserDao userDao = sqlSession.getMapper(UserDao.class);
    List<User> userList = userDao.findByCondition4(ids);
    System.out.println(userList);
    sqlSession.close();
}

注意:

foreach标签用于遍历集合,它的属性:
collection: 代表要遍历的集合元素,不要写成#{}
open: 代表语句的开始部分
close: 代表结束部分
item: 代表遍历集合的每个元素,生成的变量名
sperator: 代表分隔符
赞(3) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《Mybatis快速入门(七)-动态SQL》
文章链接:https://www.itheibai.com/archives/209
免责声明:根据《计算机软件保护条例》第十七条规定“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。”您需知晓本站所有内容资源均来源于网络,仅供用户交流学习与研究使用,版权归属原版权方所有,版权争议与本站无关,用户本人下载后不能用作商业或非法用途,需在24个小时之内从您的电脑中彻底删除上述内容,否则后果均由用户承担责任;如果您访问和下载此文件,表示您同意只将此文件用于参考、学习而非其他用途,否则一切后果请您自行承担,如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
本站是非经营性个人站点,所有软件信息均来自网络,所有资源仅供学习参考研究目的,并不贩卖软件,不存在任何商业目的及用途,网站会员捐赠是您喜欢本站而产生的赞助支持行为,仅为维持服务器的开支与维护,全凭自愿无任何强求。

评论 抢沙发

评论前必须登录!

 

养成“打赏”的好习惯,从我做起!

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册