-
Notifications
You must be signed in to change notification settings - Fork 0
Java客户端 SqlBuilder
本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,betweenNullable
在范围里面。in,inNullable
类似于。like,likeNullable
为空。isNull
不为空。isNotNull
与操作。and()
或操作。or()
非操作。not()
左括号。leftBracket()
右括号。rightBracket()
运行时当满足一定条件时,SqlBuilder会对表达式做调整以满足最终需求。具体规则如下 判断条件
操作
忽略当前元素
向左遍历,消除所有的AND/OR/NOT直到遇到不是上面3个操作符的元素
向左遍历,如果遇到左括号,则消除左括号并且忽略当前右括号
移除左边所有的AND/OR/NOT直到遇到第一个不是上面3个操作符
如果左边没有元素或左边第一个元素为左括号或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);
}