惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
Know Your Adversary
Know Your Adversary
Google DeepMind News
Google DeepMind News
A
Arctic Wolf
P
Privacy & Cybersecurity Law Blog
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
V
Visual Studio Blog
Project Zero
Project Zero
L
LangChain Blog
N
News and Events Feed by Topic
博客园 - Franky
Last Week in AI
Last Week in AI
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
T
The Exploit Database - CXSecurity.com
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
www.infosecurity-magazine.com
www.infosecurity-magazine.com
W
WeLiveSecurity
月光博客
月光博客
博客园_首页
美团技术团队
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
腾讯CDC
Latest news
Latest news
WordPress大学
WordPress大学
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Spread Privacy
Spread Privacy
Attack and Defense Labs
Attack and Defense Labs
量子位
L
LINUX DO - 热门话题
C
CERT Recently Published Vulnerability Notes
Webroot Blog
Webroot Blog
L
Lohrmann on Cybersecurity
aimingoo的专栏
aimingoo的专栏
T
Troy Hunt's Blog
Security Latest
Security Latest
小众软件
小众软件
Cloudbric
Cloudbric
Hacker News: Ask HN
Hacker News: Ask HN
S
Secure Thoughts
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
H
Hacker News: Front Page
IT之家
IT之家
Simon Willison's Weblog
Simon Willison's Weblog

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python的协程 Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server Spring AI集成MCP Client LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读 TenantLineInnerInterceptor源码解读 BaseMultiTableInnerInterceptor源码解读 Spring AI开篇 芋道源码解读之多租户 芋道源码解读之数据权限 芋道源码解读开篇 Java实现将数据导出为Word文档 OA系统的天数该怎样计算 安装MySQL8 安装MySQL5.7 RockyLinux9环境下编译MySQL8 MySQL字符集及底层原理 Java实现LDAP登录 Docker Compose IPv4和IPv6 使用虚拟机安装一个K8s集群 使用GraalVM原生编译打包SpringBoot工程 Nginx防止目录穿越 Java线程的状态 Nginx防盗链设置 使用python将excel表格转换为SQL INSERT Redis的公共操作命令 Redis数据结构之Bitfleid Redis数据结构之Bitmap Redis数据结构之GEO Redis数据结构之Hash Redis数据结构之HyperLogLog Redis数据结构之List Redis数据结构之Set Redis数据结构之Stream Redis数据结构之String Redis数据结构之ZSet 使用python压缩图片 利用Python实现Hexo站点的持续集成 Nginx设置HTTPS监听 firewalld防火墙工具的使用 Linux信号(signal)机制 MySQL5.7x 主从复制 用IP自签发一个HTTPS证书 基于Hexo实现一个静态的个人博客 RockyLinux9环境下编译MySQL5.7 Docker离线安装 MySQL数据定义语言 Docker与联合文件系统 Docker的网络 Docker的镜像操作 MySQL存储过程 MyBatis-Plus开篇 MySQL变量 MySQL视图 MySQL事务 MySQL插入修改和删除 MySQL查询 MySQL系统命令 Docker的容器操作 Docker的安装和配置 Docker容器数据卷 浅谈OAuth2.0授权原理 JVM开篇 浅谈Linux(Unix)的I/O模型 一个通用的CloseableHttpClient工厂类 JUC可重入锁ReentrantLock JUC读写锁ReadWriteLock Java的单例 Java泛型 Java8的新特性 最近最少使用算法(LRU) MySQL函数 SpringBoot配置和启动 volatile作用分析
SQL解析工具JSQLParser
Liu Zijian · 2025-02-01 · via Liu Zijian's Blog | 一个技术博客

本文未完待续…

一、引言

JSQLParser(GitHub:https://github.com/JSQLParser/JSqlParser)是一个Java语言的SQL语句解析工具,功能十分强大,它可以将SQL语句解析成为Java类的层次结构,还支持改写SQL,常见的持久层框架MyBatis-Plus就采用它作为SQL解析工具来实现某些功能。

二、JSQLParser常见类

2.1 Class Diagram

2.2 Statement

可以理解为能够表示任意一种SQL语句的对象,Select、Update、Delete、Insert都是它的子类,例如以下用法:

Statement statement = JsqlParserGlobal.parse(sql);

if (statement instanceof Insert) {
    this.processInsert((Insert) statement, index, sql, obj);
} else if (statement instanceof Select) {
    this.processSelect((Select) statement, index, sql, obj);
} else if (statement instanceof Update) {
    this.processUpdate((Update) statement, index, sql, obj);
} else if (statement instanceof Delete) {
    this.processDelete((Delete) statement, index, sql, obj);
}

2.3 Expression

是JSqlParser库中的一个核心接口,是用于表示SQL语句中的各种表达式的基类接口,通过调用对象的.toString()方法,就能看到具体的语句结构。

例如:

  1. 基本值
    • LongValue(整数值)、StringValue(字符串值)、DoubleValue(浮点数值)等。
  2. 列引用
    • Column(表示列名,如 column_nametable.column)。
  3. 运算符
    • Addition+)、Subtraction-)、Multiplication*)、Division/)等。
  4. 函数调用
    • Function(如 COUNT(*)SUBSTRING(str, 1, 2))。
  5. 条件表达式
    • EqualsTo=)、NotEqualsTo<>!=)、GreaterThan>)、LikeExpressionLIKE)等。
  6. 逻辑表达式(BinaryExpression)
    • AndExpressionAND)、OrExpressionOR)、NotExpressionNOT)。
  7. 子查询
    • SubSelect(如 (SELECT ...))。
  8. Case 表达式
    • CaseExpressionCASE WHEN ... THEN ... END)。
  9. 其他复杂表达式
    • CastExpressionCAST(... AS ...))、IntervalExpression(时间间隔)等。

2.4 Select

用于表示查询SQL语句,有三个常见子类:PlainSelect,ParenthesedSelect,SetOperationList

2.5 Update

用于表示更新的SQL语句

获得对应表

Table table = update.getTable();

获得要更新的值

List<UpdateSet> sets = update.getUpdateSets();

获取where条件

Expression expression = update.getWhere()

2.6 Delete

用于表示删除的SQL语句

获得对应表

Table table = delete.getTable();

获取where条件

Expression expression = delete.getWhere()

2.7 Insert

用于表示添加SQL语句,有以下几种常见方法

获取添加的列

List<Column> columns = insert.getColumns();

获取添加的值

Values values = insert.getValues();

获取添加时冲突进行更新的结构

INSERT INTO ... VALUES ...ON DUPLICATE KEY UPDATE ...
List<UpdateSet> duplicateUpdateColumns = insert.getDuplicateUpdateSets();

insert select的结构,获取select

INSERT ... SELECT ...
Select select = insert.getSelect();

2.8 PlainSelect

用于表示最常规的那种查询结构,例如:

select...from...join...where...

获取select后面的结构

List<SelectItem<?>> selectItems = plainSelect.getSelectItems();

获取select语句的where结构

Expression where = plainSelect.getWhere();

获取查询的from后的结构(表,子查询等)

FromItem fromItem = plainSelect.getFromItem();

存在连接查询时,获取连接查询(left/right/inner)join后的结构

List<Join> joins = plainSelect.getJoins();

2.9 SetOperationList

用于表示多个select语句通过unionunion all连接在一起的联合查询SQL对象

select...from...
union all
select...from...
union all
select...from...

将语句拆分,获取构成它的若干select

SetOperationList operationList = (SetOperationList) selectBody;
List<Select> selectBodyList = operationList.getSelects();

2.10 ParenthesedSelect

用于表示子查询,被小括号包裹的一个查询结构,例如:

(select....from...) as t

“去括号”,得到一个PlainSelect

ParenthesedSelect parenthesedSelect = (ParenthesedSelect) selectBody;
Select select = parenthesedSelect.getSelect();

2.11 FromItem

接口,from后面的SQL结构,ParenthesedSelect,ParenthesedFromItem,Table都是它的实现

FromItem fromItem = plainSelect.getFromItem();

if (fromItem instanceof Table) {
    
}
else if (fromItem instanceof ParenthesedSelect) {
    
}
else if (fromItem instanceof ParenthesedFromItem) {
    
}

2.12 Table

用于表示SQL中的表

2.13 ParenthesedFromItem

小括号包裹的可被查询的结构,但不是子查询,不常用,例如小括号包裹的join:

(tab1 join tab2)

2.14 SelectItem

用于表示select语句中,select和from之间的部分,例如:

select
    fun(1, 2) as a,
    (select x from ...) as b,
    name as c,
    exists (...) AS d
from t
List<SelectItem<?>> selectItems = plainSelect.getSelectItems();

selectItems.forEach(selectItem -> {
    Expression expression = selectItem.getExpression();

    if (expression instanceof Select) {
        
    }
    else if (expression instanceof Function) {

    }
    else if (expression instanceof ExistsExpression) {

    }
});

2.15 BinaryExpression

泛指比较符号:and or = >= =<,这种结构左右连接着其他结构。EqualsTo,OrExpression,AndExpression都是它的子类。

获取左右两侧的结构:

BinaryExpression expression = (BinaryExpression) obj;
Expression left = expression.getLeftExpression();
Expression right = expression.getRightExpression();

2.16 InExpression

x in (...)

获取右侧的结构,可能是子查询或(*,*,*...)

InExpression expression = (InExpression) obk;
Expression inExpression = expression.getRightExpression();

2.17 ExistsExpression

exists (...)

获取右侧结构

ExistsExpression expression = (ExistsExpression) obj;
Expression e = expression.getRightExpression() ;

2.18 NotExpression

not,与其他的配合使用,例如:

not in (...)

not exists (...)

获取not后面的结构,会提取出in exists等结构

NotExpression expression = (NotExpression) obj;
Expression e = expression.getExpression();

2.19 Parenthesis

代表小括号()括起来的结构

(...)

去括号,拿到括号中的结构:

Parenthesis expression = (Parenthesis) obj;
Expression e = expression.getExpression();

2.20 Function

函数结构,通常会获取参数,对参数进行操作

fun()
ExpressionList<?> parameters = function.getParameters();
if (parameters != null) {
    parameters.forEach(expression -> {
        if (expression instanceof Select) {
            
        } 
        else if (expression instanceof Function) {
            
        } 
    });
}

2.21 EqualsTo

=

2.22 OrExpression

or

2.23 AndExpression

and

2.24 Join

SQL中连接查询的join结构,从Select中获得。

获取join后的结构,一般可能是表也可能是子查询

FromItem joinItem = join.getRightItem();

判断是否为隐式内连接

join.isSimple();

判断是内/左/右连接

join.isRight();
join.isInner();
join.isLeft();

获取join的on条件

Collection<Expression> originOnExpressions = join.getOnExpressions();

改写join的on条件

join.setOnExpressions(onExpressions);

2.25 Column

用于表示SQL中的字段对象,例如从一个Insert对象获取SQL要添加的全部字段:name,age,tenant_id

INSERT INTO t_user (name, age, tenant_id) VALUES ('liming', 15), ('zhaoying', 16)
List<Column> columns = insert.getColumns();

2.26 UpdateSet

UpdateSet是一种类似xx = xx, ...的结构,出现在update的set后面

update user set username = 5 where id = 1 
List<UpdateSet> sets = update.getUpdateSets();

也能在insert语句处理添加的数据冲突的情况时,出现在ON DUPLICATE KEY UPDATE后面

INSERT INTO table_name (col1, col2) VALUES (val1, val2)
ON DUPLICATE KEY UPDATE col1 = val3, col2 = col4 + 1;
List<UpdateSet> duplicateUpdateColumns = insert.getDuplicateUpdateSets();

2.27 ExpressionList

Expression列表,本质上是List<Expression>,当insert语句values后面批量跟了多组值,就能得到这种结构。

('liming', 15), ('zhaoying', 16)
Values values = insert.getValues();
ExpressionList<Expression> expressions = (ExpressionList<Expression>) values.getExpressions();

2.28 ParenthesedExpressionList

继承自ExpressionList,本质上也是List<Expression>,一种带着括号的Expression结构,例如获取insert语句values后面的值就能得到这种结构

('liming', 15)
Values values = insert.getValues();
ExpressionList<Expression> expressions = (ExpressionList<Expression>) values.getExpressions();
if (expressions instanceof ParenthesedExpressionList) {
    // ParenthesedExpressionList
} else {
    // ExpressionList
}

附:类路径

net.sf.jsqlparser.statement.Statement
net.sf.jsqlparser.statement.select.Select
net.sf.jsqlparser.statement.update.Update
net.sf.jsqlparser.statement.delete.Delete
net.sf.jsqlparser.statement.insert.Insert
net.sf.jsqlparser.schema.Table
net.sf.jsqlparser.expression.Expression
net.sf.jsqlparser.statement.select.ParenthesedSelect
net.sf.jsqlparser.statement.select.SetOperationList
net.sf.jsqlparser.statement.select.SelectItem
net.sf.jsqlparser.expression.BinaryExpression
net.sf.jsqlparser.expression.operators.relational.InExpression
net.sf.jsqlparser.expression.operators.relational.ExistsExpression
net.sf.jsqlparser.expression.NotExpression
net.sf.jsqlparser.expression.Parenthesis
net.sf.jsqlparser.statement.select.ParenthesedFromItem
net.sf.jsqlparser.statement.select.FromItem
net.sf.jsqlparser.expression.Function
net.sf.jsqlparser.expression.operators.relational.EqualsTo
net.sf.jsqlparser.expression.operators.conditional.OrExpression
net.sf.jsqlparser.expression.operators.conditional.AndExpression
net.sf.jsqlparser.statement.select.Join
net.sf.jsqlparser.schema.Column
net.sf.jsqlparser.expression.operators.relational.ExpressionList
net.sf.jsqlparser.expression.operators.relational.ParenthesedExpressionList