一般地,实现动态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. Umbraco examine search media folder 中的pdf文件

    可以参考的文章 http://sleslie.me/2015/selecting-media-using-razor-slow-performance-examine-to-the-rescue/ h ...

  2. Json文件转Excel

    先创建一个web项目,在根目录放置需要转换的json文件,直接读取静态Json文件加载数据进行转换,代码如下: string Json = string.Empty; List<object&g ...

  3. 讨论:研发团队到底应该是制定OKR还是制定KPI?

    在讨论之前我们先来了解两个概念: 一.KPI KPI是一套绩效管理的方法.全称为:Key Performance Indicator.中文叫:关键绩效指标. KPI,和我们的“任务分解”不同.任务分解 ...

  4. CV codes代码分类整理合集 《转》

    from:http://www.sigvc.org/bbs/thread-72-1-1.html 一.特征提取Feature Extraction:   SIFT [1] [Demo program] ...

  5. surface shader相关参数,命令

    https://docs.unity3d.com/Manual/SL-SurfaceShaders.html 说明: 注意下surfaceshader相关开关选项,input结构体全部可用参数 goo ...

  6. DataGridView DataSource INotifyPropertyChanged 避免闪烁的方法

    代码说话: dgvPosition就是需要避免闪烁的DataGridView 主要是加2段代码 1.SetStyle 2.datagridview设置DoubleBuffered属性为True pub ...

  7. 洛谷P2759 奇怪的函数

    P2759 奇怪的函数 题目描述 使得 x^x 达到或超过 n 位数字的最小正整数 x 是多少? 输入输出格式 输入格式: 一个正整数 n 输出格式: 使得 x^x 达到 n 位数字的最小正整数 x ...

  8. Django一些鲜为人知的操作

    目录: - Django ORM执行原生SQL - QuerySet方法大全 一.Django ORM执行原生SQL # extra # 在QuerySet的基础上继续执行子语句 # extra(se ...

  9. python进阶07 MySQL

    python进阶07 MySQL 一.MySQL基本结构 1.认识MySQL #MySQL不是数据库,它是数据库管理软件 #MySQL如何组织数据 #如何进入MySQL数据库 #其他注意事项 #以表格 ...

  10. 038 Count and Say 数数并说

    数数并说序列是一个整数序列,第二项起每一项的值为对前一项的计数,其前五项如下:1.     12.     113.     214.     12115.     1112211 被读作 " ...