浅谈MyBatis3 DynamicSql风格语法使用指南
主要演示DynamicSql风格代码如何使用,基本能应对大部分使用场景。DynamicSql基本介绍点我查看。
本文主要沿着增、删、改、查的思路进行介绍,尽量涵盖日常使用所需。
我这里还是要推荐一下大家看官方文档,尽量有问题先找官方文档教程,除非写的跟屎一样,但大概率不会。
本次使用的是mybatis-dynamic-sql1.2.1版本
org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 mysql mysql-connector-java 8.0.22 org.mybatis.generator mybatis-generator-core 1.4.0 org.mybatis.dynamic-sql mybatis-dynamic-sql 1.2.1
查
查询我尽量贴上SQL语句对照着java代码,方便读者阅读和理解。
而且基本都实际运行过,确保没有问题。
查询指定列
SELECT id,label,value FROM sys_dict
importstaticcom.twj.spirngbasics.server.mapper.SysDictDynamicSqlSupport.*;//注意导入对应DynamicSqlSupport包的静态属性 SelectStatementProviderselectStatement=SqlBuilder.select(id,label,value) .from(sysDict) .build() .render(RenderingStrategies.MYBATIS3); Listtest=sysDictMapper.selectMany(selectStatement);
下面完全等价于上面代码,推荐上方写法,代码更整洁。
SelectStatementProviderselectStatement=SqlBuilder.select(SysDictDynamicSqlSupport.id,SysDictDynamicSqlSupport.label,SysDictDynamicSqlSupport.value) .from(SysDictDynamicSqlSupport.sysDict) .build() .render(RenderingStrategies.MYBATIS3); Listlist=sysDictMapper.selectMany(selectStatement);
可以看到DynamicSql的使用结构完全与sql语句一样,真香。
查询所有列
SELECT id,label,value,sort....... FROM sys_dict
SelectStatementProviderselectStatement=SqlBuilder.select(SysDictMapper.selectList) .from(SysDictDynamicSqlSupport.sysDict) .build() .render(RenderingStrategies.MYBATIS3); Listlist=sysDictMapper.selectMany(selectStatement);
条件查询
SELECT * FROM sys_dict WHERE label='男' ORlabel='女' ORDERBY `value`ASC
SelectStatementProviderselectStatement=SqlBuilder.select(SysDictMapper.selectList) .from(SysDictDynamicSqlSupport.sysDict) .where(label,isEqualTo("男")) .or(label,isEqualTo("女")) .orderBy(value) .build() .render(RenderingStrategies.MYBATIS3); Listlist=sysDictMapper.selectMany(selectStatement);
java这里稍微注意一下,isEqualTo的包引用路径是在org.mybatis.dynamic.sql.SqlBuilder包下,可以像之前一样importstaticorg.mybatis.dynamic.sql.SqlBuilder.*;引入所有静态方法。
排序:
- 升序:默认MySQL可以不加ASC即为升序排序,DynamicSql也是如此,指定列即可;
- 降序:调用descending()即可,以上方例子为例,原orderBy(value)改为orderBy(value.descending())即可。
SELECT * FROM sys_dict WHERE labelIN('女','男') ORDERBY `value`
SelectStatementProviderselectStatement=SqlBuilder.select(SysDictMapper.selectList) .from(SysDictDynamicSqlSupport.sysDict) .where(label,isIn("女","男")) .orderBy(value) .build() .render(RenderingStrategies.MYBATIS3); Listlist=sysDictMapper.selectMany(selectStatement);
where条件查询还有很多我就不一一例举了,我这里有一张官方偷来的表格:
Condition | Example | Result |
---|---|---|
Between | where(foo,isBetween(x).and(y)) | wherefoobetween?and? |
Equals | where(foo,isEqualTo(x)) | wherefoo=? |
GreaterThan | where(foo,isGreaterThan(x)) | wherefoo>? |
GreaterThanorEquals | where(foo,isGreaterThanOrEqualTo(x)) | wherefoo>=? |
In | where(foo,isIn(x,y)) | wherefooin(?,?) |
In(caseinsensitive) | where(foo,isInCaseInsensitive(x,y)) | whereupper(foo)in(?,?)(theframeworkwilltransformthevaluesforxandytouppercase) |
LessThan | where(foo,isLessThan(x)) | wherefoo |
LessThanorEquals | where(foo,isLessThanOrEqualTo(x)) | wherefoo<=? |
Like | where(foo,isLike(x)) | wherefoolike?(theframeworkDOESNOTaddtheSQLwildcardstothevalue-youwillneedtodothatyourself) |
Like(caseinsensitive) | where(foo,isLikeCaseInsensitive(x)) | whereupper(foo)like?(theframeworkDOESNOTaddtheSQLwildcardstothevalue-youwillneedtodothatyourself,theframeworkwilltransformthevalueofxtouppercase) |
NotBetween | where(foo,isNotBetween(x).and(y)) | wherefoonotbetween?and? |
NotEquals | where(foo,isNotEqualTo(x)) | wherefoo<>? |
NotIn | where(foo,isNotIn(x,y)) | wherefoonotin(?,?) |
NotIn(caseinsensitive) | where(foo,isNotInCaseInsensitive(x,y)) | whereupper(foo)notin(?,?)(theframeworkwilltransformthevaluesforxandytouppercase) |
NotLike | where(foo,isLike(x)) | wherefoonotlike?(theframeworkDOESNOTaddtheSQLwildcardstothevalue-youwillneedtodothatyourself) |
NotLike(caseinsensitive) | where(foo,isNotLikeCaseInsensitive(x)) | whereupper(foo)notlike?(theframeworkDOESNOTaddtheSQLwildcardstothevalue-youwillneedtodothatyourself,theframeworkwilltransformthevalueofxtouppercase) |
NotNull | where(foo,isNotNull()) | wherefooisnotnull |
Null | where(foo,isNull()) | wherefooisnull |
子查询
SELECT * FROM user_resource WHERE idIN( SELECT resource_id FROM user_role_resource WHERE role_id='1' )
SelectStatementProviderselectStatement=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); Listlist=userResourceMapper.selectMany(selectStatement);
子查询还有很多,我这里又有一张官方偷来的表格:
Condition | Example | Result |
---|---|---|
Equals | where(foo,isEqualTo(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo=(selectbarfromtable2wherebar=?) |
GreaterThan | where(foo,isGreaterThan(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo>(selectbarfromtable2wherebar=?) |
GreaterThanorEquals | where(foo,isGreaterThanOrEqualTo(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo>=(selectbarfromtable2wherebar=?) |
In | where(foo,isIn(select(bar).from(table2).where(bar,isLessThan(x))) | wherefooin(selectbarfromtable2wherebar) |
LessThan | where(foo,isLessThan(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo<(selectbarfromtable2wherebar=?) |
LessThanorEquals | where(foo,isLessThanOrEqualTo(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo<=(selectbarfromtable2wherebar=?) |
NotEquals | where(foo,isNotEqualTo(select(bar).from(table2).where(bar,isEqualTo(x))) | wherefoo<>(selectbarfromtable2wherebar=?) |
NotIn | where(foo,isNotIn(select(bar).from(table2).where(bar,isLessThan(x))) | wherefoonotin(selectbarfromtable2wherebar) |
根据业务逻辑添加条件
详细看代码
QueryExpressionDSL.QueryExpressionWhereBuilderbuilder=SqlBuilder.select(SysDictMapper.selectList) .from(SysDictDynamicSqlSupport.sysDict) .where(); if(x) builder.where(label,isIn("女","男")); if(y) builder.where(row,...); SelectStatementProviderselectStatement=builder.build().render(RenderingStrategies.MYBATIS3); List list=sysDictMapper.selectMany(selectStatement);
连接查询
有前面的基础,连接查询其实异曲同工,我这里直接贴上官方示例代码:
SelectStatementProviderselectStatement=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语句了
新增一条
SysDictsysDict=newSysDict(); sysDict.setLabel("测试"); sysDict.setValue("0"); sysDict.setType("test"); sysDict.setSort(0); sysDict.setDescription("测试"); sysDict.insert("SYSTEM"); introw=sysDictMapper.insert(sysDict); System.out.println("成功插入条数:"+row);
批量新增
Listlist=newArrayList<>(); for(inti=1;i<10;i++){ SysDictsysDict=newSysDict(); sysDict.setLabel("测试"); sysDict.setValue(String.valueOf(i)); sysDict.setType("test"); sysDict.setSort(i); sysDict.setDescription("测试"); sysDict.insert("SYSTEM"); list.add(sysDict); } MultiRowInsertStatementProvider 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); introws=sysDictMapper.insertMultiple(multiRowInsert); System.out.println("成功插入条数:"+rows);
批量新增这里需要注意的是map的添加,也可以不加,但我在使用过程中出现过不加map导致批量新增出现某些必填字段明明赋值了数据库却报没有不能为空,猜测应该是转换成sql语句时into与value没有一一对应,加上map就没问题了。
PS:.map可以直接从xxxDictMapper.insert()中copy过来。
删
//根据主键删除 sysDictMapper.deleteByPrimaryKey(""); //条件删除 DeleteStatementProviderdeleteStatement=deleteFrom(SysDictDynamicSqlSupport.sysDict) .where(SysDictDynamicSqlSupport.type,isEqualTo("test")) .build() .render(RenderingStrategies.MYBATIS3); sysDictMapper.delete(deleteStatement);
改
常用的简单更新主要是下面两种:
//根据主键对所有属性进行更新 sysDictMapper.updateByPrimaryKey(sysDict); //根据主键对不为null的属性进行更新 sysDictMapper.updateByPrimaryKeySelective(sysDict);
复杂一点点的:
UpdateStatementProviderupdateStatement=update(SysDictDynamicSqlSupport.sysDict) .set(remake).equalToNull() .where(type,isEqualTo("test")) .build() .render(RenderingStrategies.MYBATIS3); introws=sysDictMapper.update(updateStatement); System.out.println("成功更新条数:"+rows);
注意set方法,常用的方法有以下:
- set(column).equalToNull()将对应列更新为null;
- set(column).equalTo(Tvalue)将对应列更新为value;
- set(column).equalToWhenPresent(Tvalue)如果value不能null的话更新列;
- set(column).equalTo(BasicColumnrightColumn)将一列的值设置为另一列的值,还可以对其加,减等操作。
到此这篇关于浅谈MyBatis3DynamicSql风格语法使用指南的文章就介绍到这了,更多相关MyBatis3DynamicSql风格内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。