Java的MyBatis框架中对数据库进行动态SQL查询的教程

网友投稿 185 2023-07-19


Java的MyBatis框架中对数据库进行动态SQL查询的教程

其实MyBatis具有的一个强大的特性之一通常是它的动态 SQL 能力。 如果你有使用 JDBC 或其他 相似框架的经验,你就明白要动态的串联 SQL 字符串在一起是十分纠结的,确保不能忘了空格或在列表的最后省略逗号。Mybatis中的动态 SQL 可以彻底处理这种痛苦。对于动态SQL,最通俗简单的方法就是我们自己在硬编码的时候赋予各种动态行为的判断,而在Mybatis中,用一种强大的动态 SQL 语 言来改进这种情形,这种语言可以被用在任意映射的 SQL 语句中。动态 SQL 元素和使用 jsTL 或其他相似的基于 XML 的文本处理器相似。MyBatis 采用功能强大的基于 OGNL 的表达式来消除其他元素。

我们常用的几个节点元素有if,choose(when, otherwise),trim(where, if),foreach。真正使用下来我感觉有点像XSLT(文章后面会顺带提一下~)的用法。

(1)if 的用法

在ViisitMapper的分页配置中,如果pageIndex>-1 and pageSize>-1的时候就加入相应的分页SQL,否则就不添加(默认取全部),如下:

resultType="Visitor">

select * from (

) t

limit #{pageStart}, #{pageSize}

select * from Visitor where

status>0

order by ${orderFieldStr} ${orderDirectionStr}

因为我们的参数pageIndex与pageSize都是int值所以可以这样直接判断,如果是对象实例我们可以利用null判断来进行一些动态逻辑的控制,具体实际开发中就要看业务需求了。这里我认为要注意的是别十分顺手的吧and写成&&,这个在配置中不会被识别~。

(2)choose (when, otherwise)的用法

choose when 主要在多个条件的情况下只满足其中一个条件的应用场景中使用,例如这里就构建一个query条件,分别传递id,name与createTime。假设我们查询Visitor表时,如果VisitorId有值则,使用Id查询,如果VisitorName有值则采用VisitName查询,如下,还是在david.mybatis.demo.IVisitorOperation接口类中添加List getListChooseWhenDemo(BasicQueryArgs args)方法。在VisitorMapper中添加相应的的select节点配置:

package david.mybatis.demo;

import java.util.List;

import david.mybatis.model.BasicQueryArgs;

import david.mybatis.model.PagenateArgs;

import david.mybatis.model.Visitor;

import david.mybatis.model.VisitorWithRn;

public interface IVisitorOperation {

/*

* 添加访问者

*/

public int add(Visitor visitor);

/*

* 删除访问者

*/

public int delete(int id);

/*

* 更新访问者

*/

public int update(Visitor visitor);

/*

* 查询访问者

*/

public Visitor query(int id);

/*

* 查询List

*/

public List getList();

/*

* 分页查询List

*/

public List getListByPagenate(PagenateArgs args);

/*

* 分页查询List(包含Rownum)

*/

public List getListByPagenateWithRn(PagenateArgs args);

/*

* 基础查询

*/

public Visitor basicQuery(int id);

/*

* 动态条件查询(choose,when)实例

*/

public List getListChooseWhenDemo(BasicQueryArgs args);

/*

* 动态条件查询(where,if)实例

*/

public List getListWhereDemo(BasicQueryArgs args);

/*

* 动态查询(foreach)实例

*/

public List getListForeachDemo(List ids);

}

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from Visitor

parameterType="BasicQueryArgs">

status=#{queryStatus}

and id=#{queryId}

and name like #{queryName}

and createTime>= #{queryTime}

(3)where if (trim)的用法

where关键词的好处是在于,如果有相应的过滤条件的话,它知道在适当的时候插入where关键词。而且它也知道在何时该去掉相应的AND与OR的连接符,主要应对如下情景

resultType="Blog">

SELECT * FROM BLOG

WHERE

state = #{state}

AND title like #{title}

AND author_name like #{author.name}

不会因为所有条件不满足变为

resultType="Blog">

SELECT * FROM BLOG

WHERE

或者因为没有满足第一个条件,单单满足后面的条件变成

resultType="Blog">

SELECT * FROM BLOG

WHERE

AND title like ‘someTitle'

所以针对这种我们可以在建立choose when条件示例,同样在IVisitorOperation接口类中加入相应的方法public List getListWhereDemo(BasicQueryArgs args),把VisitorMapper配置文件中的相对应配置加上去如下:

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from Visitor

parameterType="BasicQueryArgs">

status>0

and id=#{queryId}

and name like=#{queryName}

and createTime>=#{queryTime}

(4)foreach的用法

在常用的动态SQL中我们有个业务场景是要where id in 一大串的ID,像这种情况我们就可以用到foreach啦,不必自己辛辛苦苦去拼接Id字符串啦。同样的步骤还是在IVisitorOperation接口类中加入相应的方法public List getListForeachDemo(List ids),然后再对应的Mapper文件中配置上相应的节点元素信息,如下:

PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

select * from Visitor

where status>0 and id in

${item}

最后你只需要在DemoRun中建立相应的测试方法,Mybatis里面的动态SQL也就完成啦,下面测试用的DemoRun方法

/*

* 动态查询foreach实例

*/

public static void getListForeachDemo(List ids) {

SqlSession session = MybatisUtils.getSqlSession();

IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);

List ls = vOperation.getListForeachDemo(ids);

for (Visitor visitor : ls) {

System.out.println(visitor);

}

}

/*

* 动态查询where if实例

*/

public static void getListWhereCondition(int id, String name, Date createTime) {

name = name == "" ? null : name;

SqlSession session = MybatisUtils.getSqlSession();

BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);

IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);

List ls = vOperation.getListWhereDemo(args);

if (ls.size() == 0)

System.out.println("查无匹配!");

else {

for (Visitor visitor : ls) {

System.out.println(visitor);

}

}

}

/*

* 动态查询choose when实例

*/

public static void getListChooseWhenDemo(int id, String name, Date createTime) {

name = name == "" ? null : name;

SqlSession session = MybatisUtils.getSqlSession();

BasicQueryArgs args = new BasicQueryArgs(id, name, createTime);

IVisitorOperation vOperation = session.getMapper(IVisitorOperation.class);

List ls = vOperation.getListChooseWhenDemo(args);

if (ls.size() == 0)

System.out.phttp://rintln("查无匹配!");

else {

for (Visitor visitor : ls) {

System.out.println(visitor);

}

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java的MyBatis框架中MyBatis Generator代码生成器的用法
下一篇:Java使用JavaMail发送邮件的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~