JSqlParser是一個與RDBMS無關的SQL語句解析器,支持多種方言,例如Oracle、SQL Server、MySQL、MariaDB、PostgreSQL、H2等。
JSqlParser將SQL語句轉換為JAVA類的可遍歷層次結構,還可以用于通過API從Java代碼創建SQL語句。現在普遍使用的MyBatis-plus以及分頁插件PageHelper都是借助JSqlParser實現SQL解析的。
JSqlParser源碼主要包括以下幾類對象:
- expression:SQL構建相關類,比如Function、EqualsTo、AndExpression、InExpression等表達式用于構建SQL。
- parser:SQL解析相關類,比如CCJSqlParserUtil、CCJSqlParserManager、抽象語法樹對象等。
- schema:主要存放數據庫schema相關的類 ,比如Database、Table、Column等。
- statement:封裝了數據庫操作對象,create、insert、delete、select、drop、alter、truncate等。
- util:各種工具類、不同DB版本、SQL標準等處理類,如SelectUtils、DatabaseType等。
解析SQL
對于下列SQL語句:
SELECT name, age, score FROM user WHERE id=1;
轉換為Java對象層次結構為:
解析SQL代碼實例:
public static void parseSQL() {
//Select語句樣本
String sql1 = "select t1.f1,t1.f2,t2.id,count(*) from table1 t1 left join table2 t2 right join (select * from table3) t3 where t1.id='10' or (t1.id between 1 and 3 and t1.id>'12') group by t.f1 order by t.f1 desc,tf2 asc limit 1,20";
//Insert語句樣本
String sql2 = "insert into table(f1,f2) values (1,2)";
//Create語句樣本
String sql3 = "CREATE TABLE `sys_user` (n" +
" `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '編號',n" +
" `name` varchar(200) DEFAULT '' COMMENT '名稱',n" +
" `age` tinyint(4) DEFAULT NULL COMMENT '年齡',n" +
" `create_by` varchar(64) DEFAULT '' COMMENT '創建者',n" +
" `create_time` datetime DEFAULT NULL COMMENT '創建時間',n" +
" `update_by` varchar(64) DEFAULT '' COMMENT '更新者',n" +
" `update_time` datetime DEFAULT NULL COMMENT '更新時間',n" +
" `remark` varchar(500) DEFAULT NULL COMMENT '備注',n" +
" PRIMARY KEY (`id`)n" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶表';";
try {
//處理Select語句
Select select = (Select) CCJSqlParserUtil.parse(sql1);
TablesNamesFinder tablesNamesFinder = new TablesNamesFinder();
List<String> tableList = tablesNamesFinder.getTableList(select);
// 獲取到查詢sql中的所有表名
System.out.println("表名:" + tableList);
//處理Insert語句
Insert insert = (Insert) CCJSqlParserUtil.parse(sql2);
System.out.println("插入的表" + insert.getTable());
System.out.println("插入的列" + insert.getColumns());
System.out.println("插入的值" + insert.getItemsList());
//處理Create Table語句
Statement statement = CCJSqlParserUtil.parse(sql3);
if (statement instanceof CreateTable) {
CreateTable createTable = ((CreateTable) statement);
Table table = createTable.getTable();
//通過columnDefinition進而可以獲取列名、數據類型等
List<ColumnDefinition> columnDefinitions = createTable.getColumnDefinitions();
System.out.println(table);
System.out.println(columnDefinitions);
}
} catch (Exception e) {
e.printStackTrace();
}
}
輸出如下:
表名:[table1, table2, table3]
插入的表table
插入的列[f1, f2]
插入的值(1, 2)
`sys_user`
[`id` bigint (20) NOT NULL AUTO_INCREMENT COMMENT '編號', `username` varchar (200) DEFAULT '' COMMENT '名稱', `age` tinyint (4) DEFAULT NULL COMMENT '年齡', `create_by` varchar (64) DEFAULT '' COMMENT '創建者', `create_time` datetime DEFAULT NULL COMMENT '創建時間', `update_by` varchar (64) DEFAULT '' COMMENT '更新者', `update_time` datetime DEFAULT NULL COMMENT '更新時間', `remark` varchar (500) DEFAULT NULL COMMENT '備注']
創建SQL
/**
* 創建SQL查詢語句
*
* @throws JSQLParserException
*/
public static void createSQL() throws JSQLParserException {
// 單表全量
Table table = new Table("sys_user");
//查詢所有列
Select select = SelectUtils.buildSelectFromTable(table);
// SELECT * FROM sys_user
System.out.println(select);
// 指定列查詢
Select buildSelectFromTableAndExpressions = SelectUtils.buildSelectFromTableAndExpressions(new Table("test"), new Column("col1"), new Column("col2"));
// SELECT col1, col2 FROM sys_user
System.out.println(buildSelectFromTableAndExpressions);
// WHERE =
EqualsTo equalsTo = new EqualsTo(); // 等于表達式
// 設置表達式左邊值
equalsTo.setLeftExpression(new Column(table, "user_id"));
// 設置表達式右邊值
equalsTo.setRightExpression(new StringValue("123456"));
// 轉換為更細化的Select對象
PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
plainSelect.setWhere(equalsTo);
// SELECT * FROM sys_user WHERE sys_user.user_id = '123456'
System.out.println(plainSelect);
// WHERE != <>
NotEqualsTo notEqualsTo = new NotEqualsTo();
notEqualsTo.setLeftExpression(new Column(table, "user_id")); // 設置表達式左邊值
notEqualsTo.setRightExpression(new StringValue("123456"));// 設置表達式右邊值
PlainSelect plainSelectNot = (PlainSelect) select.getSelectBody();
plainSelectNot.setWhere(notEqualsTo);
System.out.println(plainSelectNot);// SELECT * FROM sys_user WHERE sys_user.user_id <> '123456'
// 其他運算符, 參考上面代碼添加表達式即可
GreaterThan gt = new GreaterThan(); // ">"
GreaterThanEquals geq = new GreaterThanEquals(); // ">="
MinorThan mt = new MinorThan(); // "<"
MinorThanEquals leq = new MinorThanEquals();// "<="
IsNullExpression isNull = new IsNullExpression(); // "is null"
isNull.setNot(true);// "is not null"
LikeExpression nlike = new LikeExpression();
nlike.setNot(true); // "not like"
Between bt = new Between();
bt.setNot(true);// "not between"
// WHERE LIKE
LikeExpression likeExpression = new LikeExpression(); // 創建Like表達式對象
likeExpression.setLeftExpression(new Column("username")); // 表達式左邊
likeExpression.setRightExpression(new StringValue("張%")); // 右邊表達式
PlainSelect plainSelectLike = (PlainSelect) select.getSelectBody();
plainSelectLike.setWhere(likeExpression);
System.out.println(plainSelectLike); // SELECT * FROM sys_user WHERE username LIKE '張%'
// WHERE IN
Set<String> deptIds = Sets.newLinkedHashSet(); // 創建IN范圍的元素集合
deptIds.add("0001");
deptIds.add("0002");
ItemsList itemsList = new ExpressionList(deptIds.stream().map(StringValue::new).collect(Collectors.toList())); // 把集合轉變為JSQLParser需要的元素列表
InExpression inExpression = new InExpression(new Column("dept_id "), itemsList); // 創建IN表達式對象,傳入列名及IN范圍列表
PlainSelect plainSelectIn = (PlainSelect) select.getSelectBody();
plainSelectIn.setWhere(inExpression);
System.out.println(plainSelectIn); // SELECT * FROM sys_user WHERE dept_id IN ('0001', '0002')
// WHERE BETWEEN AND
Between between = new Between();
between.setBetweenExpressionStart(new LongValue(18)); // 設置起點值
between.setBetweenExpressionEnd(new LongValue(30)); // 設置終點值
between.setLeftExpression(new Column("age")); // 設置左邊的表達式,一般為列
PlainSelect plainSelectBetween = (PlainSelect) select.getSelectBody();
plainSelectBetween.setWhere(between);
System.out.println(plainSelectBetween); // SELECT * FROM sys_user WHERE age BETWEEN 18 AND 30
// WHERE AND 多個條件結合,都需要成立
AndExpression andExpression = new AndExpression(); // AND 表達式
andExpression.setLeftExpression(equalsTo); // AND 左邊表達式
andExpression.setRightExpression(between); // AND 右邊表達式
PlainSelect plainSelectAnd = (PlainSelect) select.getSelectBody();
plainSelectAnd.setWhere(andExpression);
System.out.println(plainSelectAnd); // SELECT * FROM sys_user WHERE sys_user.user_id = '123456' AND age BETWEEN 18 AND 30
// WHERE OR 多個條件滿足一個條件成立返回
OrExpression orExpression = new OrExpression();// OR 表達式
orExpression.setLeftExpression(equalsTo); // OR 左邊表達式
orExpression.setRightExpression(between); // OR 右邊表達式
PlainSelect plainSelectOr = (PlainSelect) select.getSelectBody();
plainSelectOr.setWhere(orExpression);
System.out.println(plainSelectOr); // SELECT * FROM sys_user WHERE sys_user.user_id = '123456' OR age BETWEEN 18 AND 30
// ORDER BY 排序
OrderByElement orderByElement = new OrderByElement(); // 創建排序對象
orderByElement.isAsc(); // 設置升序排列 從小到大
orderByElement.setExpression(new Column("col01")); // 設置排序字段
PlainSelect plainSelectOrderBy = (PlainSelect) select.getSelectBody();
plainSelectOrderBy.addOrderByElements(orderByElement);
// SELECT * FROM sys_user WHERE sys_user.user_id = '123456' OR age BETWEEN 18 AND 30 ORDER BY col01
System.out.println(plainSelectOrderBy);
}
輸出如下:
SELECT * FROM sys_user
SELECT col1, col2 FROM sys_user
SELECT * FROM sys_user WHERE sys_user.user_id = '123456'
SELECT * FROM sys_user WHERE sys_user.user_id <> '123456'
SELECT * FROM sys_user WHERE username LIKE '張%'
SELECT * FROM sys_user WHERE dept_id IN ('0001', '0002')
SELECT * FROM sys_user WHERE age BETWEEN 18 AND 30
SELECT * FROM sys_user WHERE sys_user.user_id = '123456' AND age BETWEEN 18 AND 30
SELECT * FROM sys_user WHERE sys_user.user_id = '123456' OR age BETWEEN 18 AND 30
SELECT * FROM sys_user WHERE sys_user.user_id = '123456' OR age BETWEEN 18 AND 30 ORDER BY col01