Mybatis实现动态组装查询条件,仿SQL模式⽬的:
以前⽐较习惯使⽤Hibernate,后来觉得mybatis不能按我想要的⾃动组装为SQL查询条件,所以提供该⼯具类;
效果图:
如图所⽰,根据条件⾃动组装查询条件,下⾯来说⼀下实现⽅法:
1. ServiceImpl书写注意项
Page<SysLogin> resultPage = null;
try {
PageHelper.CurrentPage(), PageSize());
// 判断是否有分页
if (ObjectHelper.Direction())
&& ObjectHelper.Properties())) {
specification.Properties(),
}
/
/ 判断是否存在逻辑删除筛选
String sqlStr = specification.sql();
if (sqlStr.indexOf("deleted") == -1) {
specification.eq("deleted", "0");
}
resultPage = this.sysLoginMapper.page(specification.sql());
} catch (Exception e) {
result = wFailure("数据错误", "在获取分页列表时发⽣异常。");
<(SimpleLogFormater.Message(), e));
return result;
}
2. Mapper.java 书写
查询条件⾮Map对象,直接就是SQL语句了;
/**
* 分页查询数据
*
* @return
*/
Page<T> page(String sqlStr);
3. 关于XML的配置,会拼装SQL语句
附:SQL拼装⼯具类
/**
* @Description: (⽤⼀句话描述该⽂件做什么)
* @author heliang
* @date 2018-7-6 下午6:43:42
* @version V2.1
*/
2.basemon;
2.base.helper.ObjectHelper;
/**
* @ClassName: Specification
* @Description: (这⾥⽤⼀句话描述这个类的作⽤)
* @author heliang
* @date 2018-7-6 下午6:43:42
* @version V2.1 * Update Logs: * Name: * Date: * Description: 初始化
*/
public class Specification {
private StringBuilder where = new StringBuilder();
private String groupBy;
private String having;
private String orderBy;
public StringBuilder getWhere() {
return where;
}
public void setWhere(StringBuilder where) {
this.where = where;
}
public String getGroupBy() {
return groupBy;
}
public void setGroupBy(String groupBy) {
}
public String getHaving() {
return having;
}
public void setHaving(String having) {
this.having = having;
}
public String getOrderBy() {
return orderBy;
}
public void setOrderBy(String orderBy) {
}
public Specification addOrderBy(String sort, String order) {
if (!isEmpty(sort) && !isEmpty(order)) {
}
return this;
}
public Specification orLike(String value, String columns) {
if (!isEmpty(value)) {
StringBuffer strBuf = new StringBuffer("");
for (String column : columns.split(",")) {
strBuf.append(ObjectHelper.underscoreName(column) + " like '%"                        + value + "%' or ");
}
String orLikeStr = strBuf.substring(0, strBuf.lastIndexOf("or"));
where.append(" and (" + orLikeStr + ")");
}
return this;
}
public Specification eq(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column) + " = '"                    + sqlParam(value) + "'");
}
return this;
}
public Specification ne(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " != '" + sqlParam(value) + "'");
}
return this;
}
public Specification like(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " like '%" + sqlParam(value) + "%'");
}
return this;
}
public Specification notLike(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " not like '%" + sqlParam(value) + "%'");
}
return this;
}
public Specification in(String column, values) {
if (!isEmpty(values)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " in (" + inValuesString(values) + ")");
}
return this;
}
public Specification notIn(String column, values) {
if (!isEmpty(values)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " not in (" + inValuesString(values) + ")");
}
return this;
}
public Specification gt(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column) + " > '"                    + sqlParam(value) + "'");
}
return this;
}
public Specification gte(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " >= '" + sqlParam(value) + "'");
}
return this;
}
public Specification lt(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column) + " < '"                    + sqlParam(value) + "'");
}
return this;
}
public Specification lte(String column, String value) {
if (!isEmpty(value)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " <= '" + sqlParam(value) + "'");
}
return this;
}
public Specification between(String column, String from, String to) {
if (isEmpty(from) && isEmpty(to)) {
return this;
}
if (isEmpty(to)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " >= '" + sqlParam(from) + "'");
} else if (isEmpty(from)) {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " <= '" + sqlParam(to) + "'");
} else {
where.append(" and " + ObjectHelper.underscoreName(column)
+ " between '" + sqlParam(from) + "' and '" + sqlParam(to)
+ "'");
}
return this;
}
public String sql() {
StringBuilder sql = new StringBuilder("");
final int a = 4;
final int b = 5;
if (where.length() > a) {
sql.append(" " + where.substring(b));
}
if (!isEmpty(groupBy)) {
sql.append(" group by " + groupBy);
}
if (!isEmpty(having)) {
sql.append(" having " + having);
}
if (!isEmpty(orderBy)) {
sql.append(" order by " + orderBy);
}
String();
}
public String toString() {
return sql();
}
private static boolean isEmpty(String value) {
return value == null || "".equals(value) || im().length() == 0;
}
private static boolean isEmpty(String[] values) {
if (values == null || values.length == 0) {
return true;
}
for (String value : values) {
if (!isEmpty(value)) {
return false;
}
}
return true;
}
private static String inValuesString(String[] values) {
StringBuilder string = new StringBuilder();
for (String value : values) {
if (isEmpty(value)) {
continue;
}
string.append('\'');
string.append(value);
string.append('\'');
string.append(',');
}
if (string.length() > 0) {
string.deleteCharAt(string.length() - 1);
}
String();
}
private static String sqlParam(String sqlParam) {
placeAll("([';]+|(--)+)", "");
}
}
附:ObjectHelper ⼯具源码:
2.base.helper;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* Object帮助类功能:此类提供处理 <Object>对象⼀系列⽅法 *
* @author 贺亮
*
*/
public class ObjectHelper {
/**
* 将id数组转换为id集合
*
* @param ids
* @return
*/
public static List<Long> initIds(String[] ids) {
List<Long> list = new ArrayList<Long>();
list.add(-1L);
for (int i = 0; i < ids.length; i++) {
list.add(Long.valueOf(ids[i]));
}
return list;
}
/**
* 组装条件
*
* @param str
* @return
*/
public static List<String> strToList(String str) {
if (isEmpty(str)) {
return null;
}
String[] strs = str.split(",");
List<String> list = new ArrayList<String>();
for (int i = 0; i < strs.length; i++) {
list.add(strs[i]);
}
return list;
}
/**
* 判断这个Object是否为Null或长度为0
*
* @param obj
* @return
*/
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof Collection) {
return ((Collection<?>) obj).isEmpty();
}
if (obj instanceof String) {
return ((String) obj).equalsIgnoreCase("null")
| ((String) obj).trim().toString().equals("");
}
if (obj instanceof StringBuffer) {
return ((StringBuffer) obj).length() == 0;
}
if (Class().isArray()) {
try {
Object[] a = (Object[]) obj;
boolean b = true;
for (Object o : a) {
b = b & isEmpty(o);
if (!b) {
break;
}
}
return b;
} catch (ClassCastException e) {
}
}
return false;
}
/**
* 判断这个Object是否不为Null或长度不为0
*
* @param obj
* @return
*/
public static boolean isNotEmpty(Object obj) {
return !isEmpty(obj);
}
/**
* 返回⾸字母⼤写单词
*
* @param str
* @return
*/
public static String lcyFirstLetterToUpper(String str) {
placeFirst(str.substring(0, 1), str.substring(0, 1)
.toUpperCase());
}
/**
* 转换为下划线
*
sort of my superpower
* @param camelCaseName
* @return
*/
public static String underscoreName(String camelCaseName) {
StringBuilder result = new StringBuilder();
if (camelCaseName != null && camelCaseName.length() > 0) {
result.append(camelCaseName.substring(0, 1).toLowerCase());
for (int i = 1; i < camelCaseName.length(); i++) {
char ch = camelCaseName.charAt(i);
if (Character.isUpperCase(ch)) {
result.append("_");
result.LowerCase(ch));
} else {
result.append(ch);
}
}
}
String();
}
/**
* 转换为驼峰
*
* @param underscoreName
* @return
*/
public static String camelCaseName(String underscoreName) {
StringBuilder result = new StringBuilder();
if (underscoreName != null && underscoreName.length() > 0) {
boolean flag = false;
for (int i = 0; i < underscoreName.length(); i++) {
char ch = underscoreName.charAt(i);
if ("_".charAt(0) == ch) {
flag = true;
} else {
if (flag) {
result.UpperCase(ch));
flag = false;
} else {
result.append(ch);
}
}
}
}
String();
}
public static void main(String[] args) {
System.out.println(underscoreName("loginName"));
}
}
这样就可以做到动态⽣成查询条件,复杂的查询条件也不会去改动XML配置了。mybatis原理:参数解析与SQL动态组装过程
mybatis执⾏sql之前,需要经过参数解析、sql动态组装等过程,本⽂主要聊聊mybatis的:(1)参数解析原理及其过程
(2)sql动态组装原理及其过程
⼀、数据准备
1.实体类,省略了set、get⽅法
public class User {
private String id;
private String username;
private String password;
private Integer isValid;
}
2.mapper接⼝UserMapper,可以看作是⼀个根据⽤户名和密码的登录接⼝
User getUserByUsernameAndPassword(@Param("name") String username, @Param("pwd") String password);
3.mapper映射
<select id="getUserByUsernameAndPassword" resultType="com.qxf.pojo.User">
select id,username,password,is_valid as isValid from t_user
<where>
<if test="name != null and name != ''">
username = #{name}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。