Skip to content

Java客户端 SqlBuilder

He, Jiehui edited this page Aug 1, 2016 · 2 revisions

简介

本wiki说明SqlBuilder在Dal Java Client中如何支持可以为null的参数。

为什么要支持这种做法请参考Support generate sql with possible null parameter

所有操作都定义在AbstractSqlBuilder里面

支持的元素

=

等于。equal,equalNullable

!=

不等于。notEqual,notEqualNullable

>

大于。greaterThan,greaterThanNullable

>=

大于等于。greaterThanEquals,greaterThanEqualsNullable

<

小于。lessThan,lessThanNullable

<=

小于等于。lessThanEquals,lessThanEqualsNullable

BETWEEN

在两者之间。between,betweenNullable

IN

在范围里面。in,inNullable

LIKE

类似于。like,likeNullable

IS NULL

为空。isNull

IS NOT NULL

不为空。isNotNull

AND

与操作。and()

OR

或操作。or()

NOT

非操作。not()

左括号。leftBracket()

右括号。rightBracket()

可空元素规则

运行时当满足一定条件时,SqlBuilder会对表达式做调整以满足最终需求。具体规则如下 判断条件

操作

遇到空值

忽略当前元素

向左遍历,消除所有的AND/OR/NOT直到遇到不是上面3个操作符的元素

遇到右括号

向左遍历,如果遇到左括号,则消除左括号并且忽略当前右括号

移除左边所有的AND/OR/NOT直到遇到第一个不是上面3个操作符

遇到AND或者OR

如果左边没有元素或左边第一个元素为左括号或AND/OR/NOT,则忽略当前AND/OR

如果左边第一个元素为左括号或者AND/OR/NOT,则忽略当前AND/OR

例子。下例中对b和d的操作传入null,则结果里面会自动去掉相关的sql语句。

@Test
public void testNullValue() throws SQLException {
    List<String> in = new ArrayList<String>();
    in.add("12");
    in.add("12");
     
    SelectSqlBuilder builder = new SelectSqlBuilder("People", DatabaseCategory.MySql, false);
     
    builder.select("PeopleID","Name","CityID");
     
    builder.equal("a", "paramValue", Types.INTEGER);
    builder.and().in("b", in, Types.INTEGER);
    builder.and().likeNullable("b", null, Types.INTEGER);
    builder.and().between("c", "paramValue1", "paramValue2", Types.INTEGER);
    builder.and().betweenNullable("d", null, "paramValue2", Types.INTEGER);
    builder.and().isNull("sss");
    builder.orderBy("PeopleID", false);
     
    String sql = builder.buildFirst();
     
    String expect_sql = "SELECT `PeopleID`, `Name`, `CityID` FROM People "
            + "WHERE a = ? AND b in ( ?, ? ) AND c BETWEEN ? AND ? "
            + "AND sss IS NULL ORDER BY `PeopleID` DESC limit 0,1";
     
    Assert.assertEquals(expect_sql, sql);
}