欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

浅谈MyBatis3 DynamicSql风格语法使用指南

程序员文章站 2022-03-23 18:54:06
主要演示dynamicsql风格代码如何使用,基本能应对大部分使用场景。dynamicsql基本介绍点我查看。本文主要沿着增、删、改、查的思路进行介绍,尽量涵盖日常使用所需。我这里还是要推荐一下大家看...

主要演示dynamicsql风格代码如何使用,基本能应对大部分使用场景。dynamicsql基本介绍点我查看。

本文主要沿着增、删、改、查的思路进行介绍,尽量涵盖日常使用所需。

我这里还是要推荐一下大家看,尽量有问题先找官方文档教程,除非写的跟屎一样,但大概率不会。

本次使用的是mybatis-dynamic-sql1.2.1版本

<!-- 集成mybatis -->
<dependency>
 <groupid>org.mybatis.spring.boot</groupid>
 <artifactid>mybatis-spring-boot-starter</artifactid>
 <version>2.1.3</version>
</dependency>
<dependency>
 <groupid>mysql</groupid>
 <artifactid>mysql-connector-java</artifactid>
 <version>8.0.22</version>
</dependency>
<!-- mybatis 生成器 -->
<dependency>
 <groupid>org.mybatis.generator</groupid>
 <artifactid>mybatis-generator-core</artifactid>
 <version>1.4.0</version>
</dependency>
<!-- mybatis 动态sql支持 -->
<dependency>
 <groupid>org.mybatis.dynamic-sql</groupid>
 <artifactid>mybatis-dynamic-sql</artifactid>
 <version>1.2.1</version>
</dependency>


查询我尽量贴上sql语句对照着java代码,方便读者阅读和理解。

而且基本都实际运行过,确保没有问题。

查询指定列

select 
 id,label,value 
from 
 sys_dict
import static com.twj.spirngbasics.server.mapper.sysdictdynamicsqlsupport.*; //注意导入对应dynamicsqlsupport包的静态属性

selectstatementprovider selectstatement = sqlbuilder.select(id, label, value)
  .from(sysdict)
  .build()
  .render(renderingstrategies.mybatis3);
list<sysdict> test = sysdictmapper.selectmany(selectstatement);

下面完全等价于上面代码,推荐上方写法,代码更整洁。

selectstatementprovider selectstatement = sqlbuilder.select(sysdictdynamicsqlsupport.id, sysdictdynamicsqlsupport.label, sysdictdynamicsqlsupport.value)
  .from(sysdictdynamicsqlsupport.sysdict)
  .build()
  .render(renderingstrategies.mybatis3);
list<sysdict> list = sysdictmapper.selectmany(selectstatement);
 

可以看到dynamicsql的使用结构完全与sql语句一样,真香。

查询所有列

select 
 id,label,value,sort.......
from 
 sys_dict
 
selectstatementprovider selectstatement = sqlbuilder.select(sysdictmapper.selectlist)
  .from(sysdictdynamicsqlsupport.sysdict)
  .build()
  .render(renderingstrategies.mybatis3);
list<sysdict> list = sysdictmapper.selectmany(selectstatement);

条件查询

select
 * 
from
 sys_dict 
where
 label = '男' 
 or label = '女' 
order by
 `value` asc
selectstatementprovider selectstatement = sqlbuilder.select(sysdictmapper.selectlist)
  .from(sysdictdynamicsqlsupport.sysdict)
  .where(label, isequalto("男"))
  .or(label,isequalto("女"))
  .orderby(value)
  .build()
  .render(renderingstrategies.mybatis3);
list<sysdict> list = sysdictmapper.selectmany(selectstatement);

java这里稍微注意一下,isequalto的包引用路径是在org.mybatis.dynamic.sql.sqlbuilder包下,可以像之前一样import static org.mybatis.dynamic.sql.sqlbuilder.*;引入所有静态方法。

排序:

  • 升序:默认mysql可以不加asc即为升序排序,dynamicsql也是如此,指定列即可;
  • 降序:调用descending()即可,以上方例子为例,原orderby(value)改为orderby(value.descending())即可。
select
 * 
from
 sys_dict 
where
 label in ( '女', '男' ) 
order by
 `value`
selectstatementprovider selectstatement = sqlbuilder.select(sysdictmapper.selectlist)
  .from(sysdictdynamicsqlsupport.sysdict)
  .where(label, isin("女", "男"))
  .orderby(value)
  .build()
  .render(renderingstrategies.mybatis3);
list<sysdict> list = sysdictmapper.selectmany(selectstatement);

where条件查询还有很多我就不一一例举了,我这里有一张官方偷来的表格:

condition example result
between where(foo, isbetween(x).and(y)) where foo between ? and ?
equals where(foo, isequalto(x)) where foo = ?
greater than where(foo, isgreaterthan(x)) where foo > ?
greater than or equals where(foo, isgreaterthanorequalto(x)) where foo >= ?
in where(foo, isin(x, y)) where foo in (?,?)
in (case insensitive) where(foo, isincaseinsensitive(x, y)) where upper(foo) in (?,?) (the framework will transform the values for x and y to upper case)
less than where(foo, islessthan(x)) where foo < ?
less than or equals where(foo, islessthanorequalto(x)) where foo <= ?
like where(foo, islike(x)) where foo like ? (the framework does not add the sql wild cards to the value - you will need to do that yourself)
like (case insensitive) where(foo, islikecaseinsensitive(x)) where upper(foo) like ? (the framework does not add the sql wild cards to the value - you will need to do that yourself, the framework will transform the value of x to upper case)
not between where(foo, isnotbetween(x).and(y)) where foo not between ? and ?
not equals where(foo, isnotequalto(x)) where foo <> ?
not in where(foo, isnotin(x, y)) where foo not in (?,?)
not in (case insensitive) where(foo, isnotincaseinsensitive(x, y)) where upper(foo) not in (?,?) (the framework will transform the values for x and y to upper case)
not like where(foo, islike(x)) where foo not like ? (the framework does not add the sql wild cards to the value - you will need to do that yourself)
not like (case insensitive) where(foo, isnotlikecaseinsensitive(x)) where upper(foo) not like ? (the framework does not add the sql wild cards to the value - you will need to do that yourself, the framework will transform the value of x to upper case)
not null where(foo, isnotnull()) where foo is not null
null where(foo, isnull()) where foo is null

子查询

select
 * 
from
 user_resource 
where
 id in (
 select
 resource_id 
 from
 user_role_resource 
 where
 role_id = '1' 
 )
selectstatementprovider selectstatement = sqlbuilder.select(userresourcemapper.selectlist)
  .from(userresourcedynamicsqlsupport.userresource)
  .where(userresourcedynamicsqlsupport.id, isin(
    select(userroleresourcedynamicsqlsupport.resourceid)
      .from(userroleresourcedynamicsqlsupport.userroleresource)
      .where(userroleresourcedynamicsqlsupport.roleid, isequalto("1"))))
  .build()
  .render(renderingstrategies.mybatis3);
list<userresource> list = userresourcemapper.selectmany(selectstatement);

子查询还有很多,我这里又有一张官方偷来的表格:

condition example result
equals where(foo, isequalto(select(bar).from(table2).where(bar, isequalto(x))) where foo = (select bar from table2 where bar = ?)
greater than where(foo, isgreaterthan(select(bar).from(table2).where(bar, isequalto(x))) where foo > (select bar from table2 where bar = ?)
greater than or equals where(foo, isgreaterthanorequalto(select(bar).from(table2).where(bar, isequalto(x))) where foo >= (select bar from table2 where bar = ?)
in where(foo, isin(select(bar).from(table2).where(bar, islessthan(x))) where foo in (select bar from table2 where bar < ?)
less than where(foo, islessthan(select(bar).from(table2).where(bar, isequalto(x))) where foo < (select bar from table2 where bar = ?)
less than or equals where(foo, islessthanorequalto(select(bar).from(table2).where(bar, isequalto(x))) where foo <= (select bar from table2 where bar = ?)
not equals where(foo, isnotequalto(select(bar).from(table2).where(bar, isequalto(x))) where foo <> (select bar from table2 where bar = ?)
not in where(foo, isnotin(select(bar).from(table2).where(bar, islessthan(x))) where foo not in (select bar from table2 where bar < ?)

根据业务逻辑添加条件

详细看代码

queryexpressiondsl<selectmodel>.queryexpressionwherebuilder builder = sqlbuilder.select(sysdictmapper.selectlist)
  .from(sysdictdynamicsqlsupport.sysdict)
  .where();

if (x)
 builder.where(label, isin("女", "男"));

if (y)
 builder.where(row,...);

selectstatementprovider selectstatement = builder.build().render(renderingstrategies.mybatis3);

list<sysdict> list = sysdictmapper.selectmany(selectstatement);

连接查询

有前面的基础,连接查询其实异曲同工,我这里直接贴上官方示例代码:

selectstatementprovider selectstatement = select(ordermaster.orderid, orderdate, orderdetail.linenumber, orderdetail.description, orderdetail.quantity)
   .from(ordermaster, "om")
   .join(orderdetail, "od").on(ordermaster.orderid, equalto(orderdetail.orderid))
   .build()
   .render(renderingstrategies.mybatis3);

目前支持四种连接类型:

  • .join(...) 内连接
  • .leftjoin(...) 左外连接
  • .rightjoin(...) 右外连接
  • .fulljoin(...) 全连接


新增这里就不附上sql语句了

新增一条

sysdict sysdict = new sysdict();
sysdict.setlabel("测试");
sysdict.setvalue("0");
sysdict.settype("test");
sysdict.setsort(0);
sysdict.setdescription("测试");
sysdict.insert("system");
int row = sysdictmapper.insert(sysdict);
system.out.println("成功插入条数:" + row);

批量新增

list<sysdict> list = new arraylist<>();
for (int i = 1; i < 10; i++) {
 sysdict sysdict = new sysdict();
 sysdict.setlabel("测试");
 sysdict.setvalue(string.valueof(i));
 sysdict.settype("test");
 sysdict.setsort(i);
 sysdict.setdescription("测试");
 sysdict.insert("system");
 list.add(sysdict);
}
multirowinsertstatementprovider<sysdict> multirowinsert = sqlbuilder.insertmultiple(list)
  .into(sysdictdynamicsqlsupport.sysdict)
  .map(id).toproperty("id")
  .map(createdby).toproperty("createdby")
  .map(createdtime).toproperty("createdtime")
  .map(updateby).toproperty("updateby")
  .map(updatetime).toproperty("updatetime")
  .map(dele).toproperty("dele")
  .map(remake).toproperty("remake")
  .map(spare1).toproperty("spare1")
  .map(value).toproperty("value")
  .map(label).toproperty("label")
  .map(type).toproperty("type")
  .map(description).toproperty("description")
  .map(sort).toproperty("sort")
  .build()
  .render(renderingstrategies.mybatis3);

int rows = sysdictmapper.insertmultiple(multirowinsert);
system.out.println("成功插入条数:" + rows);

批量新增这里需要注意的是map的添加,也可以不加,但我在使用过程中出现过不加map导致批量新增出现某些必填字段明明赋值了数据库却报没有不能为空,猜测应该是转换成sql语句时into与value没有一一对应,加上map就没问题了。

ps:.map可以直接从xxxdictmapper.insert()中copy过来。


//根据主键删除
sysdictmapper.deletebyprimarykey("");

//条件删除
deletestatementprovider deletestatement = deletefrom(sysdictdynamicsqlsupport.sysdict)
  .where(sysdictdynamicsqlsupport.type, isequalto("test"))
  .build()
  .render(renderingstrategies.mybatis3);
sysdictmapper.delete(deletestatement);


常用的简单更新主要是下面两种:

//根据主键对所有属性进行更新
sysdictmapper.updatebyprimarykey(sysdict);
//根据主键对不为null的属性进行更新
sysdictmapper.updatebyprimarykeyselective(sysdict);

复杂一点点的:

updatestatementprovider updatestatement = update(sysdictdynamicsqlsupport.sysdict)
  .set(remake).equaltonull()
  .where(type, isequalto("test"))
  .build()
  .render(renderingstrategies.mybatis3);

int rows = sysdictmapper.update(updatestatement);
system.out.println("成功更新条数:" + rows);

注意set方法,常用的方法有以下:

  • set(column).equaltonull() 将对应列更新为null;
  • set(column).equalto(t value)将对应列更新为value;
  • set(column).equaltowhenpresent(t value)如果value不能null的话更新列;
  • set(column).equalto(basiccolumn rightcolumn)将一列的值设置为另一列的值,还可以对其加,减等操作。

到此这篇关于浅谈mybatis3 dynamicsql风格语法使用指南的文章就介绍到这了,更多相关mybatis3 dynamicsql风格内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: MyBatis3 DynamicSql