以面向對象的方式看待sql
sql語句由好多部分組成。
把每一部分抽象出類。
where語句分析
有如下幾個sql語句:
select * from Student where age>18;
select * from Student where age>18 and sex=man
select * from Student where age>18 or sex=man
select * from Student where sex=man group by class
select * from Student where sex=man group by class having teachers=5
select * from Student where age>18 order by name
select * from Student where age>18 order by name limit 8
select * from Student where age>18 order by name limit 8 offset 2
有如下特征:
也就是where語句由以下幾個部分組成。
- 單個條件
- 多個條件的組合
- group by 以及 group by ... having
- order by
- limit
- offset
ps:
入口: getQuery
getQuery 根據where提供的信息,拼接成sql語句:
由上圖可以看出,此處的where從句分為如下幾個部分:
- where后面的條件從句
- group by后面的一堆屬性
- having 后面的條件從句
- order by后面的一堆屬性
1. 條件從句
條件的管理(conditionGroup,havingGroup):
where提供如下幾個方法來接收參數:
public Where<TModel> and(SQLCondition condition) {
conditionGroup.and(condition);
return this;
}
public Where<TModel> or(SQLCondition condition) {
conditionGroup.or(condition);
return this;
}
public Where<TModel> andAll(List<SQLCondition> conditions) {
conditionGroup.andAll(conditions);
return this;
}
public Where<TModel> andAll(SQLCondition... conditions) {
conditionGroup.andAll(conditions);
return this;
}
從以上代碼可以看出,conditionGroup實際來處理這些條件。
conditionGroup是什么?
conditionGroup相當于一個工具類,它可以接收SQLCondition,以指定的操作符(and,or)將他們拼接起來,方便where使用。
舉個例子:
-
添加條件
-
sql語句
2. 屬性的拼接
group by和order by的拼接
效果等同于:name,age