zl程序教程

您现在的位置是:首页 >  后端

当前栏目

MyBatis where标签

mybatis 标签 where
2023-06-13 09:12:03 时间
细心的读者可能会发现,我们在《MyBatis choose、when和otherwise语句》一节的 SQL 语句中加入了一个条件 1=1 ,如果没有加入这个条件,那么可能就会变成下面这样一条错误的语句。


SELECT id,name,url,age,country FROM website AND name LIKE CONCAT( % ,#{name}, % )

显然以上语句会出现 SQL 语法异常,但加入 1=1 这样的条件又非常奇怪,所以 MyBatis 提供了 where 标签。

where 标签主要用来简化 SQL 语句中的条件判断,可以自动处理 AND/OR 条件,语法如下。


 where 

 if test= 判断条件 

 AND/OR ...

 /if 

 /where 

if 语句中判断条件为 true 时,where 关键字才会加入到组装的 SQL 里面,否则就不加入。where 会检索语句,它会将 where 后的第一个 SQL 条件语句的 AND 或者 OR 关键词去掉。

要求:根据网站名称或网址对网站进行模糊查询(本节示例基于《第一个MyBatis程序》一节的代码实现)。

WebsiteMapper.xml 代码如下。


 select id= selectWebsite resultType= net.biancheng.po.Website 

 select id,name,url from website

 where 

 if test= name != null 

 AND name like #{name}

 /if 

 if test= url!= null 

 AND url like #{url}

 /if 

 /where 

 /select 

WebsiteMapper 类中方法如下。


public List Website selectWebsite(Website website);

测试类代码如下。


public class Test {

 public static void main(String[] args) throws IOException {

 // 读取配置文件mybatis-config.xml

 InputStream config = Resources.getResourceAsStream( mybatis-config.xml // 根据配置文件构建

 SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);

 // 通过SqlSessionFactory创建SqlSession

 SqlSession ss = ssf.openSession();

 Website site = new Website();

 site.setname( 编程 

 List Website siteList = ss.selectList( net.biancheng.mapper.WebsiteMapper.selectWebsite , site);

 for (Website ws : siteList) {

 System.out.println(ws);

}

输出结果如下。

DEBUG [main] ==   Preparing: SELECT id,name,url,age,country FROM website WHERE  name LIKE CONCAT( % ,?, % )
DEBUG [main] == Parameters: 编程(String)
DEBUG [main] ==  Total: 1
Website[id=1,name=编程帮,url=https://www.biancheng.net/,age=10,country=CN]

24120.html

Mybatis