Mybatis编写sql案例

本文涉及的产品
云原生网关 MSE Higress,422元/月
任务调度 XXL-JOB 版免费试用,400 元额度,开发版规格
注册配置 MSE Nacos/ZooKeeper,182元/月
简介: 列举开发中常用的sql编写案例

[toc]

列举开发中常用的sql编写案例

返回受影响行数


@Update({
   "update VirtualWarehouse set deleted=1 where id=#{virtualWarehouse.id}"})
@Options(useGeneratedKeys=true )
Long  deleteVirtualWarehouse(@Param("virtualWarehouse") VirtualWarehouse virtualWarehouse);

for循环


@Select({
""})
List findWarehouseListByIds(List ids);



### 遍历Set

```java
@Select({"<script>",        
"select 3  as status  ,'可用' as statusName, 
case COUNT(*) when null  then 0 else COUNT(*) end as 
statusCount from Warehouse",       
" where organizationId in ( ",        
" <foreach collection='collection' item='item' open='(' close=')' separator=','>",       
"       #{item}",        
"</foreach>",       
")",       
"</script>"})
WarehouseStatusCount 
findAvailableStatusWarehouseCount(Set<Long> organizationIds);

If语句


@Update({
          
"<script>",     
    "update VirtualWarehouse set ",   
    "name=#{virtualWarehouse.name} ",    
    " , updateTime=getdate()",     
    "<if test=\" virtualWarehouse.description !=null  and           virtualWarehouse.description !='' \" > ",   
     "   description=#{virtualWarehouse.description} ",  
    "</if>",   
    " where id=#{virtualWarehouse.id}",    
"</script>"
})
@Options(useGeneratedKeys = true)Long updateVirtualWarehouse(@Param("virtualWarehouse") VirtualWarehouse virtualWarehouse);

If-Else语句


@Select({
   
    "<script>",
    " select * from user ",
    "<where>",
    "<choose>",
    "   <when  test=\" user.name !=null and user.name !='' \" >",
    "       and name like CONCAT('%' , #{user.name} , '%')",
    "   </when>",
    "   <otherwise>",
    "       and name =#{currentUserName} ",
    "   </otherwise>",
    "</choose>",
    "</where>",
    "</script>"
})
List<User> findUser(@Param("user") User user, @Param("currentUserName") String currentUserName);

like 模糊查询

@Select({
   
"<script>",      
"   select count(id)  from Warehouse warehouse  ",     
"<where>",      
" organizationId in (",    
" <foreach collection='organizationIds' item='item' open='(' close=')' separator=','>",     
"       #{item}",    
"</foreach>",       
")",   
"   <if test=\" warehouse.id !=null and warehouse.id !=0 
\" >" ,          
" and  Warehouse.id=#{warehouse.id}" ,    
"</if>",      
"   <if test=\" warehouse.name !=null and warehouse.name 
!='' \" >" ,           
" and  Warehouse.name like CONCAT('%' , 
#{
   warehouse.name} , '%') " ,       
"</if>",     
"   <if test=\" warehouse.type !=null and 
warehouse.type!=0 \" >" ,        
" and  Warehouse.type=#{warehouse.type}" ,     
"   </if>",     
"</where>",    
"</script>",})
Integer countFindWarehouseList(@Param("warehouse") Warehouse warehouse ,   @Param("organizationIds") Set<Long> organizationIds);

或者


 sku.name like '%'+ #{
   keywords} + '%'  ",

if判断中带for循环


/** 
* 查询可用仓库,无分页 
*
* @return 
*/

@Select({
   "<script>",       
"select  * ",       
"from Warehouse   ",      
"<where>",       
"   <if test=\" searchProvisoDTO.name !=null and 
searchProvisoDTO.name !='' \" > ",       
"       and  name like CONCAT('%' , 
#{
   searchProvisoDTO.name} , '%') ",       
"   </if>",       
"   <if test=\" searchProvisoDTO.ids !=null  \" > ",       
"       <foreach collection='searchProvisoDTO.ids' 
item='id' open='and id in (' close=')'  separator=','>",       
"           #{id}",       
"       </foreach>",       
"   </if>",       
"</where>",       
"</script>",})List<Warehouse> 
findWarehouseListWithNoPage(@Param("searchProvisoDTO") 
SearchProvisoDTO searchProvisoDTO );

insert,返回主键


/** 
* 创建 * 
* @return 
*/
@Insert({
           
"<script>",        
" insert into DeliveryRouteStreet( deliveryRouteId , streetId , deleted , createTime) ",        
" VALUES ",        
"(#{
   deliveryRouteStreet.deliveryRouteId}, 
#{
   deliveryRouteStreet.streetId} ",        
" , 0 , now())",        
"</script>"})
@Options(useGeneratedKeys = true)
Long insertDeliveryRouteStreet(@Param("deliveryRouteStreet") 
DeliveryRouteStreet deliveryRouteStreet);

复杂分页查询


    @Select({
            "<script>",
            " SELECT u.id ,  u.account , u.username , u.mobile , u.dept_logic_id as deptId , u.org_logic_id as orgId ,  s.times , s.login_time  ",
            "<if test=\" condition.loginState !=null and condition.accounts !=null and  condition.accounts.size > 0 \" > ",
            "<choose>",
            "   <when  test=\"condition.accounts !=null and  condition.accounts.size > 0 and  condition.loginState !=null  and condition.loginState ==1 \" >",
            "       , '在线' as state ",
            "   </when>",
            "   <when  test=\"condition.accounts !=null and  condition.accounts.size > 0 and  condition.loginState !=null  and condition.loginState == 2 \" >",
            "       , '注销' as state ",
            "   </when>",
            "   <otherwise>",
            "     ,  '' as state ",
            "   </otherwise>",
            "</choose>",
            "</if>",
            " from bams_user u  LEFT JOIN login_statistics s on u.account=s.account ",
            "<where>",
            "   u.has_del=0 ",
            "   <if test=\"condition.account != null and condition.account !='' \"> and u.account like CONCAT('%' , #{condition.account} , '%') </if>",
            "   <if test=\"condition.username != null and condition.username !='' \"> and u.username like CONCAT('%' , #{condition.username} , '%') </if>",
            "   <if  test=\" condition.areaDeptId !=null  and condition.areaDeptId !='' \" >",
            "          and u.dept_logic_id like  CONCAT( #{condition.areaDeptId} , '%') ",
            "   </if>",
            "   <if test=\"condition.ids !=null and  condition.ids.size > 0 \" > ",
            "       <foreach collection='condition.ids' item='id' open='and u.id in (' close=')'  separator=','>",
            "           #{id}",
            "       </foreach>",
            "   </if>",
            "   <if test=\"condition.accounts !=null and  condition.accounts.size > 0  and condition.loginState !=null  \" > ",
            "       <choose>",
            "       <when  test=\" condition.loginState !=null   and condition.loginState == 1 \" >",
            "           <foreach collection='condition.accounts' item='id' open='and u.account in (' close=')'  separator=','>",
            "               #{id}",
            "           </foreach>",
            "       </when>",
            "       <otherwise>",
            "           <foreach collection='condition.accounts' item='id' open='and u.account not  in (' close=')'  separator=','>",
            "               #{id}",
            "           </foreach>",
            "       </otherwise>",
            "       </choose>",
            "   </if>",
            "   <if  test=\" condition.loginRecord !=null \" >",
            "       <choose>",
            "       <when  test=\" condition.loginRecord == 1 \" >",
            "           and  ( s.times &gt; 0) ",
            "       </when>",
            "       <when  test=\" condition.loginRecord == 2 \" >",
            "            and  (ISNULL(s.times) or s.times=0 ) ",
            "       </when>",
            "       </choose>",
            "   </if>",
            "   <if test=\"condition.startTime != null \"> and  s.login_time &gt;= #{condition.startTime} </if>",
            "   <if test=\"condition.endTime != null  \"> and  s.login_time &lt;= #{condition.endTime} </if>",
            "</where>",
            " order by u.id   ",
            "<if test=\"condition.needPage == true \"> ",
            "   limit #{condition.pageNum},#{condition.pageSize}  ",
            "</if>",
            "</script>"
    })
    List<LoginStatisticsDto> findPage(@Param("condition") LoginStatisticsCondition condition);

更多例子

https://www.jianshu.com/p/93ff4d89250c

目录
相关文章
|
3月前
|
SQL XML Java
通过MyBatis的XML配置实现灵活的动态SQL查询
总结而言,通过MyBatis的XML配置实现灵活的动态SQL查询,可以让开发者以声明式的方式构建SQL语句,既保证了SQL操作的灵活性,又简化了代码的复杂度。这种方式可以显著提高数据库操作的效率和代码的可维护性。
279 18
|
7月前
|
SQL 数据库 数据安全/隐私保护
数据库数据恢复——sql server数据库被加密的数据恢复案例
SQL server数据库数据故障: SQL server数据库被加密,无法使用。 数据库MDF、LDF、log日志文件名字被篡改。 数据库备份被加密,文件名字被篡改。
|
8月前
|
SQL Java 数据库连接
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
【YashanDB知识库】解决mybatis的mapper文件sql语句结尾加分号";"报错
|
7月前
|
SQL Java 数据库连接
MyBatis动态SQL字符串空值判断,这个细节99%的程序员都踩过坑!
本文深入探讨了MyBatis动态SQL中字符串参数判空的常见问题。通过具体案例分析,对比了`name != null and name != &#39;&#39;`与`name != null and name != &#39; &#39;`两种写法的差异,指出后者可能引发逻辑混乱。为避免此类问题,建议在后端对参数进行预处理(如trim去空格),简化MyBatis判断逻辑,提升代码健壮性与可维护性。细节决定成败,严谨处理参数判空是写出高质量代码的关键。
1021 0
|
3月前
|
SQL Java 数据库连接
SSM相关问题-1--#{}和${}有什么区别吗?--Mybatis都有哪些动态sql?能简述一下动 态sql的执行原理吗?--Spring支持的几种bean的作用域 Scope
在MyBatis中,`#{}`是预处理占位符,可防止SQL注入,适用于大多数参数传递场景;而`${}`是直接字符串替换,不安全,仅用于动态表名、列名等特殊场景。二者在安全性、性能及使用场景上有显著区别。
81 0
|
6月前
|
SQL XML Java
菜鸟之路Day35一一Mybatis之XML映射与动态SQL
本文介绍了MyBatis框架中XML映射与动态SQL的使用方法,作者通过实例详细解析了XML映射文件的配置规范,包括namespace、id和resultType的设置。文章还对比了注解与XML映射的优缺点,强调复杂SQL更适合XML方式。在动态SQL部分,重点讲解了`&lt;if&gt;`、`&lt;where&gt;`、`&lt;set&gt;`、`&lt;foreach&gt;`等标签的应用场景,如条件查询、动态更新和批量删除,并通过代码示例展示了其灵活性与实用性。最后,通过`&lt;sql&gt;`和`&lt;include&gt;`实现代码复用,优化维护效率。
580 5
|
7月前
|
关系型数据库 MySQL 大数据
大数据新视界--大数据大厂之MySQL 数据库课程设计:MySQL 数据库 SQL 语句调优的进阶策略与实际案例(2-2)
本文延续前篇,深入探讨 MySQL 数据库 SQL 语句调优进阶策略。包括优化索引使用,介绍多种索引类型及避免索引失效等;调整数据库参数,如缓冲池、连接数和日志参数;还有分区表、垂直拆分等其他优化方法。通过实际案例分析展示调优效果。回顾与数据库课程设计相关文章,强调全面认识 MySQL 数据库重要性。为读者提供综合调优指导,确保数据库高效运行。
|
8月前
|
SQL Java 数据库连接
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
【YashanDB 知识库】解决 mybatis 的 mapper 文件 sql 语句结尾加分号";"报错
|
8月前
|
SQL 缓存 Java
框架源码私享笔记(02)Mybatis核心框架原理 | 一条SQL透析核心组件功能特性
本文详细解构了MyBatis的工作机制,包括解析配置、创建连接、执行SQL、结果封装和关闭连接等步骤。文章还介绍了MyBatis的五大核心功能特性:支持动态SQL、缓存机制(一级和二级缓存)、插件扩展、延迟加载和SQL注解,帮助读者深入了解其高效灵活的设计理念。
|
8月前
|
SQL XML Java
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
247 0

热门文章

最新文章