Solon 3.0 引入了新的 SqlUtils 用于数据库基础操作,SqlUtils 是对 JDBC 较为原始的封装,极为反朴归真。 特性有:
- 支持事务管理
- 支持多数据源
- 支持流式输出
- 支持批量执行
- 支持存储过程
一、概述
SqlUtils 是一个轻量的数据库操作框架,简单灵活,易于阅读和维护,支持编写复杂的SQL。对于不适合使用复杂的 ORM 框架,或者需要编写复杂的 SQL 的场景,可以使用 SqlUtils 来操作数据库。
SqlUtils 总体上分为查询操作(query 开发)和更新操作(update 开头)。分别对应 JDBC 的 Statement:executeQuery() 和 Statement:executeUpdate()。
二、引入 SqlUtils
- gradle 依赖
implementation 'org.noear:solon-data-sqlutils'
- maven 依赖
<dependency>
<groupId>org.noear</groupId>
<artifactId>solon-data-sqlutils</artifactId>
</dependency>
三、配置数据源
配置数据源(具体参考:《数据源的配置与构建》)
solon.dataSources:
rock!:
class: "com.zaxxer.hikari.HikariDataSource"
jdbcUrl: jdbc:mysql://localhost:3306/rock?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true
driverClassName: com.mysql.cj.jdbc.Driver
username: root
password: 123456
之后就可以按数据源名注入 SqlUtils 了(带 ! 结尾的数据源名,为默认)
@Component
public class DemoService {
@Inject //默认数据源名
SqlUtils sqlUtils;
}
四、查询操作
查数量:
public Long findCount() throws SQLException {
return sqlUtils.sql("select count(*) from appx where app_id = ?", id).queryValue();
}
按照主键查数据:
public Appx findDataById(Integer id) throws SQLException {
return sqlUtils.sql("select * from appx where app_id = ?", id)
.queryRow(Appx.class);
}
按照自定义查询条件查数据:
public List<Appx> findDataByGroup(Integer group_id) throws SQLException {
return sqlUtils.sql("select * from appx where group_id = ?", group_id)
.queryRowList(Appx.class);
}
以上几种查询方式,都是一行代码就解决的。复杂的查询怎么办?比如管理后台的条件统计,可以先使用构建器:
public List<Appx</


740

被折叠的 条评论
为什么被折叠?



