有关mybatis的动态sql
一般地,实现动态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的更多相关文章
- MyBatis的动态SQL详解
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑,本文详解mybatis的动态sql,需要的朋友可以参考下 MyBatis 的一个强大的特性之一通常是它 ...
- Mybatis解析动态sql原理分析
前言 废话不多说,直接进入文章. 我们在使用mybatis的时候,会在xml中编写sql语句. 比如这段动态sql代码: <update id="update" parame ...
- mybatis 使用动态SQL
RoleMapper.java public interface RoleMapper { public void add(Role role); public void update(Role ro ...
- MyBatis框架——动态SQL、缓存机制、逆向工程
MyBatis框架--动态SQL.缓存机制.逆向工程 一.Dynamic SQL 为什么需要动态SQL?有时候需要根据实际传入的参数来动态的拼接SQL语句.最常用的就是:where和if标签 1.参考 ...
- 使用Mybatis实现动态SQL(一)
使用Mybatis实现动态SQL 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 写在前面: *本章节适合有Mybatis基础者观看* 前置讲解 我现在写一个查询全部的 ...
- MyBatis探究-----动态SQL详解
1.if标签 接口中方法:public List<Employee> getEmpsByEmpProperties(Employee employee); XML中:where 1=1必不 ...
- mybatis中的.xml文件总结——mybatis的动态sql
resultMap resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功. 如果sql查询字段名和pojo的属性名不一致,可以通过re ...
- mybatis.5.动态SQL
1.动态SQL,解决关联sql字符串的问题,mybatis的动态sql基于OGNL表达式 if语句,在DeptMapper.xml增加如下语句; <select id="selectB ...
- MyBatis的动态SQL详解-各种标签使用
MyBatis的动态SQL是基于OGNL表达式的,它可以帮助我们方便的在SQL语句中实现某些逻辑. MyBatis中用于实现动态SQL的元素主要有: if choose(when,otherwise) ...
- 利用MyBatis的动态SQL特性抽象统一SQL查询接口
1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...
随机推荐
- select2,利用ajax高效查询大数据列表(可搜索、可分页)
二.导入css和js到网站上 1.使用CDN,节省自己网站的流量 ? 1 2 <link href="https://cdnjs.cloudflare.com/ajax/libs/se ...
- SQL Server中的聚集索引(clustered index) 和 非聚集索引 (non-clustered index)
本文转载自 http://blog.csdn.net/ak913/article/details/8026743 面试时经常问到的问题: 1. 什么是聚合索引(clustered index) / ...
- 符号分割的字符串转换为XML
把某一符串分割的字符串转换为 XML格式: DECLARE @str NVARCHAR(MAX) = N'fd,re,45,tyu,976,qwer,gdsg,uyt' DECLARE @xml XM ...
- 深入剖析ASP.NET Core2.1部署模型,你会大吃一惊
---------------------------- 以下内容针对 ASP.NET Core2.1版本,2.2推出windows IIS进程内寄宿 暂不展开讨论---------------- ...
- nodebrew的安装与使用
创建: 2019/05/10 安装 brew install nodebrew 初始化 nodebrew setup ~/.bash_profile 里添加 export PATH=/usr/loc ...
- (function (window, document, undefined) {})(window, document)什么意思?
1.IIFE(即时调用的函数表达式),它采取以下表达式: (function (window, document, undefined) { // })(window, document); Java ...
- [UE4]用C++如何创建Box Collision
http://www.dawnarc.com/2016/08/ue4%E7%94%A8c--%E5%A6%82%E4%BD%95%E5%88%9B%E5%BB%BAbox-collision/ 在蓝图 ...
- Unity 中的坐标系
说明: 注意几点: 0 行向量右乘矩阵与列向量左乘矩阵,两个矩阵互为逆矩阵 1 法线转换与mul,mul函数左乘矩阵当列矩阵计算,右乘当行矩阵计算 2 叉乘与左右手系,左手系用左手,右手系用右手,ax ...
- java基础第六篇之常用思想、封装、继承和多态
a.累加求和思想:求1~100的和,求数组/集合中元素的和,求偶数的数,求总分 int sum=0//循环外部定义sum变量,循环里面对每个元素累加 for (; ; ) { //sum+=数据 } ...
- JQuery扩展和事件
一.jQuery事件 常用事件 blur([[data],fn]) 失去焦点 focus([[data],fn]) 获取焦点( 搜索框例子) change([[data],fn]) 当select下拉 ...