一般地,实现动态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. 如何查看Mysql event事件是否启用

    mysql> show variables like 'event_scheduler';+-----------------+-------+| Variable_name   | Value ...

  2. CSS 绝对定位与相对定位的区别

    设置为绝对定位的元素框从文档流完全删除, 并相对于其包含块定位,包含块可能是文档中的另一个元素或者是初始包含块. 元素原先在正常文档流中所占的空间会关闭,就好像该元素原来不存在一样. 元素定位后生成一 ...

  3. 小议IT公司的组织架构

    IT公司的组织结构还是很相似的,常见的部门也不多.我简单地总结了下,分享给各位.每个公司都有自己独特的组织架构,本文仅供参考.很多部门和职位的职责和权力,我也不甚了解.简单地写写,有兴趣的同学可以补充 ...

  4. es6常用方法

    一.let 和 constlet 声明变量,只在所在的块区有效,不存在变量提升:var 存在变 量提升const 声明常量,只在所在块区有效 二.变量的解构赋值1.数组的解构赋值let [a, b, ...

  5. 【JOI Camp 2015】IOIO卡片占卜——最短路

    题目 [题目描述]K 理事长是占卜好手,他精通各种形式的占卜.今天,他要用正面写着 `I` ,背面写着 `O` 的卡片占卜一下日本 IOI 国家队的选手选择情况.占卜的方法如下:1. 首先,选取五个正 ...

  6. 洛谷P1447 [NOI2010]能量采集(容斥)

    传送门 很明显题目要求的东西可以写成$\sum_{i=1}^{n}\sum_{j=1}^m gcd(i,j)*2-1$(一点都不明显) 如果直接枚举肯定爆炸 那么我们设$f[i]$表示存在公因数$i$ ...

  7. JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能

    JQuery Easyui/TopJUI 用JS创建数据表格并实现增删改查功能 html <table id="productDg"></table> &l ...

  8. JS高级学习历程-8

    2 构造函数和普通函数的区别 两者本身没有实质区别,具体看使用 new  函数();   -------->构造函数 函数();        ---------> 普通函数 <!D ...

  9. Jmeter 的 vars 和 props 用法

    meter 的 JSR223 控件是 代替 BeanShell 的新一代脚本控件,支持多种脚本语言,尤其是其中的 Groovy,更是重点推荐使用的脚本语言,本文研究其中的 vars 和 props 两 ...

  10. 【aspnetcore】添加自定义json配置文件

    打开program.cs文件,修改CreateWebHostBuilder方法: public static IWebHostBuilder CreateWebHostBuilder(string[] ...