zl程序教程

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

当前栏目

MyBatis trim标签

mybatis 标签 trim
2023-06-13 09:12:03 时间
在 MyBatis 中除了使用 if+where 实现多条件查询,还有一个更为灵活的元素 trim 能够替代之前的做法。

trim 一般用于去除 SQL 语句中多余的 AND 关键字、逗号,或者给 SQL 语句前拼接 where、set 等后缀,可用于选择性插入、更新、删除或者条件查询等操作。trim 语法格式如下。


 trim prefix= 前缀 suffix= 后缀 prefixOverrides= 忽略前缀字符 suffixOverrides= 忽略后缀字符 

 SQL语句

 /trim 

trim 中属性说明如下。


本节示例基于《第一个MyBatis程序》一节的代码实现。

下面我们利用 trim 实现与 where 元素相同的效果。

要求:根据网站名称或网址对网站进行模糊查询。

WebsiteMapper.xml 代码如下。


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

 SELECT id,name,url,age,country

 FROM website

 trim prefix= where prefixOverrides= and 

 if test= name != null and name != 

 AND name LIKE CONCAT ( % ,#{name}, % )

 /if 

 if test= url!= null 

 AND url like concat ( % ,#{url}, % )

 /if 

 /trim 

 /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( 编程 

 site.setUrl( http 

 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 ( % ,?, % ) AND url like concat ( % ,?, % )
DEBUG [main] == Parameters: 编程(String), http(String)
DEBUG [main] ==  Total: 1
Website[id=1,name=编程帮,url=https://www.biancheng.net/,age=10,country=CN]

24116.html

Mybatis