一般地,实现动态SQL都是在xml中使用等标签实现的.

我们在这里使用SQL构造器的方式, 即由abstract sql写出sql的过程, 当然感觉本质上还是一个StringBuilder, 来手动生成SQL, 只不过不需要使用sql mapping

例子 :

Model类

package lyb.model.report;

/**
* Created by lyb-pc on 17-7-19.
*/
public class UserCustomerAuthority { private String login_code;
private String login_name;
private String store_code;
private String store_name; public String getLogin_code() {
return login_code;
} public void setLogin_code(String login_code) {
this.login_code = login_code;
} public String getLogin_name() {
return login_name;
} public void setLogin_name(String login_name) {
this.login_name = login_name;
} public String getStore_code() {
return store_code;
} public void setStore_code(String store_code) {
this.store_code = store_code;
} public String getStore_name() {
return store_name;
} public void setStore_name(String store_name) {
this.store_name = store_name;
}
}

对应于一个sqlbuilder 有:

package lyb.model.report;

import org.apache.ibatis.jdbc.SQL;

import java.sql.Timestamp;
import java.util.Map; /**
* Created by lyb-pc on 17-7-19.
*/
public class UserCustomerAuthoritySqlBuilder { public String buildUserCustomerAuthorityFull(Map<String, Object> parameters) { String user_id = (String) parameters.get("user_id"); SQL a = new SQL().SELECT("user_id",
"user_name",
"customer_id",
"customer_name")
.FROM("WCC_User_Customer_Connection")
.WHERE("user_id = #{user_id}")
.GROUP_BY("customer_name",
"user_id",
"user_name",
"customer_id"); return a.toString();
}
}

这里使用SQL()构造器的语法, 把所有的原始sql转化为相应的语句, 可以动态根据参数来进行配置, 如这里的user_id就是使用了一个占位符, 在真正执行语句的时候传递给jdbc. 可以将SQL()部分作为一个StringBuilder来使用, 需要使用占位符的时候就使用#{}, 这样的模式, 在最后执行的时候会把参数进行匹配, 并加上'', 也可以直接字符串拼接.

直接使用字符串拼接的如 like和in的使用:

if (invFirstClass != null) {
a.WHERE("Inventory.cInvCode like " + "'" + invFirstClass + "%'");
} if (invSecondClass != null) {
a.WHERE("Inventory.cInvCode like " + "'" + invSecondClass + "%'");
} if (barcode != null) {
a.WHERE("Inventory.cInvAddCode = #{barcode}");
} if (cDCCode != null) {
a.WHERE("DistrictClass.cDCCode = #{cDCCode}");
} if (customer_id_list != null) {
a.WHERE("Customer.cCusCode in" + "(" + customer_id_list + ")");
} SQL t = new SQL().SELECT("Count(*) as count")
.FROM("(" + a.toString() + ") as table_temp");

如上面的代码, 展示了like和in的用法, 也有子查询的用法, 即先用一个SQL(), 作为子查询然后一层层嵌套.

实际调用的时候是 :

建立一个Mapper文件, 作为sqlSession掉用时实例化的DAO层.

package lyb.mapper;

import lyb.model.report.UserCustomerAuthority;
import lyb.model.report.UserCustomerAuthoritySqlBuilder;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.SelectProvider; import java.util.List; /**
* Created by lyb-pc on 17-7-19.
*/
public interface UserCustomerAuthorityMapper { @Results(id = "userCustomerAuthorityDefault123", value = {
@Result(property = "store_name", column = "customer_name"),
@Result(property = "store_code", column = "customer_id"),
@Result(property = "login_code", column = "user_id"),
@Result(property = "login_name", column = "user_name")
})
@SelectProvider(type = UserCustomerAuthoritySqlBuilder.class, method = "buildUserCustomerAuthorityFull")
public List<UserCustomerAuthority> getAuthority(@Param(value = "user_id") String user_id);
}

里面定义好查询结果的ResultMap, 以及使用的SqlProvider.

这样是把具体的sql实现代码给分散出来, 并且具体的代码也具有了一定的可移植性, 而不必直接编写sql的xml文件, 但是如果需要针对多数据源的切换还是需要不同的设置或者是切换语句等.

注意的是在mapper文件中, @Param的注解和sqlBuilder的对应关系.

调用为:

@RequestMapping(value = "/TestStoresListShow", method = RequestMethod.POST)
public @ResponseBody
UCCheckResponse storesListShow(@RequestBody UCCheckRequestParams params) {
UCCheckResponse response = new UCCheckResponse();
String login_code = params.getLogin_code();
SqlSession sqlSession = sessionFactory.openSession(); UserCustomerAuthorityMapper authorityMapper = sqlSession.getMapper(UserCustomerAuthorityMapper.class); List<UserCustomerAuthority> authorityList = authorityMapper.getAuthority(params.getLogin_code());
// StringBuilder customer_id_list = new StringBuilder();
// customer_id_list = JohnsonReportHelper.GetCustomerIdListBuilder(authorityList, customer_id_list); if (authorityList.size() == 0) {
response = (UCCheckResponse) JohnsonReportHelper.GenErrorResponse(response, 5002, "该用户没有对应门店数据权限");
return response;
}else {
response = (UCCheckResponse) JohnsonReportHelper.GenRightResponsePart(response);
response.setData(authorityList);
return response;
}
}

通过sqlSession得到Mapper对象, 就可以继续调用了.

有关mybatis的动态sql的更多相关文章

  1. MyBatis的动态SQL详解

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...

  2. Mybatis解析动态sql原理分析

    前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...

  3. mybatis 使用动态SQL

    RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role ro ...

  4. MyBatis框架——动态SQL、缓存机制、逆向工程

    MyBatis框架--动态SQL.缓存机制.逆向工程 一.Dynamic SQL 为什么需要动态SQL?有时候需要根据实际传入的参数来动态的拼接SQL语句.最常用的就是:where和if标签 1.参考 ...

  5. 使用Mybatis实现动态SQL(一)

    使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面:        *本章节适合有Mybatis基础者观看* 前置讲解 我现在写一个查询全部的 ...

  6. MyBatis探究-----动态SQL详解

    1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不 ...

  7. mybatis中的.xml文件总结——mybatis的动态sql

    resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...

  8. mybatis.5.动态SQL

    1.动态SQL,解决关联sql字符串的问题,mybatis的动态sql基于OGNL表达式 if语句,在DeptMapper.xml增加如下语句; <select id="selectB ...

  9. MyBatis的动态SQL详解-各种标签使用

    MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...

  10. 利用MyBatis的动态SQL特性抽象统一SQL查询接口

    1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...

随机推荐

  1. windows64位如何安装pyspider并运行

    1.下载whl文件: http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml 2.安装该文件 3.可能碰到问题,pip的版本低了,需要更新一下pip的版本.更新 ...

  2. Working Experience - How to handle the destroyed event of UserControl

    正文 问题: UserControl 如何在父窗体(程序)关闭时, 释放一些需要手动释放的资源 方法: 使用 Control.FindForm() 获取父窗体, 从而得到父窗体的 Closing/Cl ...

  3. 洛谷P2292 [HNOI2004]L语言

    传送门 建好trie树 当$dp[j]==1$当且仅当存在$dp[k]=1$且$T[k+1,j]==word[i]$ 然后乱搞就行了 //minamoto #include<iostream&g ...

  4. Java基础--环境配置、简介

    一.环境配置 1.傻瓜式安装JDK,若提示安装JRE,将其置于JDK同一安装目录即可. 2.配置JAVA_HOME, 指向JDK的安装目录.比如 JAVA_HOME  = %JDK安装目录% 3.配置 ...

  5. springboot打成jar后获取classpath下文件失败

    原文链接:https://blog.csdn.net/qq_18748427/article/details/78606432 springboot打成jar后获取classpath下文件失败 使用如 ...

  6. Spring IOC 的源码分析

    刚学习Spring的时候,印象最深的就是 DispatcherServlet,所谓的中央调度器,我也尝试从这个万能胶这里找到入口 configureAndRefreshWebApplicationCo ...

  7. path不相等的子集,父级

    SELECT a.path,b.path from comm_department_temp a INNER JOIN comm_department_temp b on a.id=b.parent_ ...

  8. 【SPOJ】Substrings

    出现次数很好处理,就是 \(right/endpos\) 集合的大小 那么,直接构建 \(SAM\) 求出每个位置的\(right\)集合大小 直接更新每个节点的\(longest\)就行了 最后短的 ...

  9. Codeforces Round #564 (Div. 2) B. Nauuo and Chess

    链接:https://codeforces.com/contest/1173/problem/B 题意: Nauuo is a girl who loves playing chess. One da ...

  10. TDH-常见运维指令

    1.查看cpu: cat /proc/cpuinfo | grep processor2.查看磁盘:df -h (查看磁盘使用率) df -i (查看iNode使用) fdisk -l (查看磁盘整体 ...