This commit is contained in:
Looly 2022-04-30 22:53:06 +08:00
parent a7ede583ec
commit 40aa543edd
36 changed files with 740 additions and 1189 deletions

View File

@ -6,6 +6,7 @@ import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.handler.BeanListHandler; import cn.hutool.db.handler.BeanListHandler;
import cn.hutool.db.handler.EntityHandler; import cn.hutool.db.handler.EntityHandler;
import cn.hutool.db.handler.EntityListHandler; import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.handler.ResultSetUtil;
import cn.hutool.db.handler.NumberHandler; import cn.hutool.db.handler.NumberHandler;
import cn.hutool.db.handler.RsHandler; import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.handler.StringHandler; import cn.hutool.db.handler.StringHandler;
@ -32,9 +33,9 @@ import java.util.Map;
* 通过给定的数据源执行给定SQL或者给定数据源和方言执行相应的CRUD操作<br> * 通过给定的数据源执行给定SQL或者给定数据源和方言执行相应的CRUD操作<br>
* 提供抽象方法getConnection和closeConnection用于自定义数据库连接的打开和关闭 * 提供抽象方法getConnection和closeConnection用于自定义数据库连接的打开和关闭
* *
* @author Luxiaolei * @author looly
*/ */
public abstract class AbstractDb implements Serializable { public abstract class AbstractDb<R extends AbstractDb<R>> implements ConnectionHolder, Serializable {
private static final long serialVersionUID = 3858951941916349062L; private static final long serialVersionUID = 3858951941916349062L;
protected final DataSource ds; protected final DataSource ds;
@ -46,7 +47,7 @@ public abstract class AbstractDb implements Serializable {
* 是否大小写不敏感默认大小写不敏感 * 是否大小写不敏感默认大小写不敏感
*/ */
protected boolean caseInsensitive = GlobalDbConfig.caseInsensitive; protected boolean caseInsensitive = GlobalDbConfig.caseInsensitive;
protected SqlConnRunner runner; protected DialectRunner runner;
// ------------------------------------------------------- Constructor start // ------------------------------------------------------- Constructor start
@ -58,36 +59,20 @@ public abstract class AbstractDb implements Serializable {
*/ */
public AbstractDb(final DataSource ds, final Dialect dialect) { public AbstractDb(final DataSource ds, final Dialect dialect) {
this.ds = ds; this.ds = ds;
this.runner = new SqlConnRunner(dialect); this.runner = new DialectRunner(dialect);
} }
// ------------------------------------------------------- Constructor end // ------------------------------------------------------- Constructor end
/**
* 获得链接根据实现不同可以自定义获取连接的方式
*
* @return {@link Connection}
* @throws SQLException 连接获取异常
*/
public abstract Connection getConnection() throws SQLException;
/**
* 关闭连接<br>
* 自定义关闭连接有利于自定义回收连接机制或者不关闭
*
* @param conn 连接 {@link Connection}
*/
public abstract void closeConnection(Connection conn);
/** /**
* 查询 * 查询
* *
* @param sql 查询语句 * @param sql 查询语句
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.1.1 * @since 3.1.1
*/ */
public List<Entity> query(final String sql, final Map<String, Object> params) throws SQLException { public List<Entity> query(final String sql, final Map<String, Object> params) throws DbRuntimeException {
return query(sql, new EntityListHandler(this.caseInsensitive), params); return query(sql, new EntityListHandler(this.caseInsensitive), params);
} }
@ -97,10 +82,10 @@ public abstract class AbstractDb implements Serializable {
* @param sql 查询语句 * @param sql 查询语句
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.1.1 * @since 3.1.1
*/ */
public List<Entity> query(final String sql, final Object... params) throws SQLException { public List<Entity> query(final String sql, final Object... params) throws DbRuntimeException {
return query(sql, new EntityListHandler(this.caseInsensitive), params); return query(sql, new EntityListHandler(this.caseInsensitive), params);
} }
@ -112,10 +97,10 @@ public abstract class AbstractDb implements Serializable {
* @param beanClass 元素Bean类型 * @param beanClass 元素Bean类型
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public <T> List<T> query(final String sql, final Class<T> beanClass, final Object... params) throws SQLException { public <T> List<T> query(final String sql, final Class<T> beanClass, final Object... params) throws DbRuntimeException {
return query(sql, new BeanListHandler<>(beanClass), params); return query(sql, new BeanListHandler<>(beanClass), params);
} }
@ -125,9 +110,9 @@ public abstract class AbstractDb implements Serializable {
* @param sql 查询语句 * @param sql 查询语句
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Entity queryOne(final String sql, final Object... params) throws SQLException { public Entity queryOne(final String sql, final Object... params) throws DbRuntimeException {
return query(sql, new EntityHandler(this.caseInsensitive), params); return query(sql, new EntityHandler(this.caseInsensitive), params);
} }
@ -137,9 +122,9 @@ public abstract class AbstractDb implements Serializable {
* @param sql 查询语句 * @param sql 查询语句
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Number queryNumber(final String sql, final Object... params) throws SQLException { public Number queryNumber(final String sql, final Object... params) throws DbRuntimeException {
return query(sql, new NumberHandler(), params); return query(sql, new NumberHandler(), params);
} }
@ -149,9 +134,9 @@ public abstract class AbstractDb implements Serializable {
* @param sql 查询语句 * @param sql 查询语句
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public String queryString(final String sql, final Object... params) throws SQLException { public String queryString(final String sql, final Object... params) throws DbRuntimeException {
return query(sql, new StringHandler(), params); return query(sql, new StringHandler(), params);
} }
@ -163,9 +148,9 @@ public abstract class AbstractDb implements Serializable {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T query(final String sql, final RsHandler<T> rsh, final Object... params) throws SQLException { public <T> T query(final String sql, final RsHandler<T> rsh, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -183,10 +168,10 @@ public abstract class AbstractDb implements Serializable {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param paramMap 参数 * @param paramMap 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.2.2 * @since 5.2.2
*/ */
public <T> T query(final String sql, final RsHandler<T> rsh, final Map<String, Object> paramMap) throws SQLException { public <T> T query(final String sql, final RsHandler<T> rsh, final Map<String, Object> paramMap) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -204,10 +189,10 @@ public abstract class AbstractDb implements Serializable {
* @param statementFunc 自定义{@link PreparedStatement}创建函数 * @param statementFunc 自定义{@link PreparedStatement}创建函数
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.7.17 * @since 5.7.17
*/ */
public <T> T query(final Func1<Connection, PreparedStatement> statementFunc, final RsHandler<T> rsh) throws SQLException { public <T> T query(final Func1<Connection, PreparedStatement> statementFunc, final RsHandler<T> rsh) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -224,9 +209,9 @@ public abstract class AbstractDb implements Serializable {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return 影响行数 * @return 影响行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int execute(final String sql, final Object... params) throws SQLException { public int execute(final String sql, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -243,9 +228,9 @@ public abstract class AbstractDb implements Serializable {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return 主键 * @return 主键
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Long executeForGeneratedKey(final String sql, final Object... params) throws SQLException { public Long executeForGeneratedKey(final String sql, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -261,10 +246,10 @@ public abstract class AbstractDb implements Serializable {
* @param sql SQL * @param sql SQL
* @param paramsBatch 批量的参数 * @param paramsBatch 批量的参数
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.4.2 * @since 5.4.2
*/ */
public int[] executeBatch(final String sql, final Iterable<Object[]> paramsBatch) throws SQLException { public int[] executeBatch(final String sql, final Iterable<Object[]> paramsBatch) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -279,10 +264,10 @@ public abstract class AbstractDb implements Serializable {
* *
* @param sqls SQL列表 * @param sqls SQL列表
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.5.6 * @since 4.5.6
*/ */
public int[] executeBatch(final String... sqls) throws SQLException { public int[] executeBatch(final String... sqls) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -297,10 +282,10 @@ public abstract class AbstractDb implements Serializable {
* *
* @param sqls SQL列表 * @param sqls SQL列表
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.4.2 * @since 5.4.2
*/ */
public int[] executeBatch(final Iterable<String> sqls) throws SQLException { public int[] executeBatch(final Iterable<String> sqls) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -317,13 +302,13 @@ public abstract class AbstractDb implements Serializable {
* *
* @param record 记录 * @param record 记录
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int insert(final Entity record) throws SQLException { public int insert(final Entity record) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.insert(conn, record); return runner.insert(conn, record)[0];
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -336,10 +321,10 @@ public abstract class AbstractDb implements Serializable {
* @param record 记录 * @param record 记录
* @param keys 需要检查唯一性的字段 * @param keys 需要检查唯一性的字段
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.10 * @since 4.0.10
*/ */
public int insertOrUpdate(final Entity record, final String... keys) throws SQLException { public int insertOrUpdate(final Entity record, final String... keys) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -353,13 +338,14 @@ public abstract class AbstractDb implements Serializable {
* 使用upsert语义插入或更新数据<br> * 使用upsert语义插入或更新数据<br>
* 根据给定的字段名查询数据如果存在则更新这些数据否则执行插入 * 根据给定的字段名查询数据如果存在则更新这些数据否则执行插入
* 如果方言未实现本方法内部会自动调用insertOrUpdate来实现功能由于upsert和insert使用有区别为了兼容性保留原有insertOrUpdate不做变动 * 如果方言未实现本方法内部会自动调用insertOrUpdate来实现功能由于upsert和insert使用有区别为了兼容性保留原有insertOrUpdate不做变动
*
* @param record 记录 * @param record 记录
* @param keys 需要检查唯一性的字段 * @param keys 需要检查唯一性的字段
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.7.21 * @since 5.7.21
*/ */
public int upsert(final Entity record, final String... keys) throws SQLException { public int upsert(final Entity record, final String... keys) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -376,13 +362,13 @@ public abstract class AbstractDb implements Serializable {
* *
* @param records 记录列表 * @param records 记录列表
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int[] insert(final Collection<Entity> records) throws SQLException { public int[] insert(final Collection<Entity> records) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.insert(conn, records); return runner.insert(conn, records.toArray(new Entity[0]));
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -393,13 +379,13 @@ public abstract class AbstractDb implements Serializable {
* *
* @param record 记录 * @param record 记录
* @return 主键列表 * @return 主键列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Object> insertForGeneratedKeys(final Entity record) throws SQLException { public List<Object> insertForGeneratedKeys(final Entity record) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.insertForGeneratedKeys(conn, record); return runner.insert(conn, record, ResultSetUtil::handleRowToList);
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -410,13 +396,13 @@ public abstract class AbstractDb implements Serializable {
* *
* @param record 记录 * @param record 记录
* @return 主键 * @return 主键
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Long insertForGeneratedKey(final Entity record) throws SQLException { public Long insertForGeneratedKey(final Entity record) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.insertForGeneratedKey(conn, record); return runner.insert(conn, record, ResultSetUtil::toLong);
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -429,9 +415,9 @@ public abstract class AbstractDb implements Serializable {
* @param field 字段名最好是主键 * @param field 字段名最好是主键
* @param value 值可以是列表或数组被当作IN查询处理 * @param value 值可以是列表或数组被当作IN查询处理
* @return 删除行数 * @return 删除行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int del(final String tableName, final String field, final Object value) throws SQLException { public int del(final String tableName, final String field, final Object value) throws DbRuntimeException {
return del(Entity.create(tableName).set(field, value)); return del(Entity.create(tableName).set(field, value));
} }
@ -440,9 +426,9 @@ public abstract class AbstractDb implements Serializable {
* *
* @param where 条件 * @param where 条件
* @return 影响行数 * @return 影响行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int del(final Entity where) throws SQLException { public int del(final Entity where) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -459,9 +445,9 @@ public abstract class AbstractDb implements Serializable {
* @param record 记录 * @param record 记录
* @param where 条件 * @param where 条件
* @return 影响行数 * @return 影响行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int update(final Entity record, final Entity where) throws SQLException { public int update(final Entity record, final Entity where) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -482,9 +468,9 @@ public abstract class AbstractDb implements Serializable {
* @param field 字段名 * @param field 字段名
* @param value 字段值 * @param value 字段值
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> Entity get(final String tableName, final String field, final T value) throws SQLException { public <T> Entity get(final String tableName, final String field, final T value) throws DbRuntimeException {
return this.get(Entity.create(tableName).set(field, value)); return this.get(Entity.create(tableName).set(field, value));
} }
@ -493,9 +479,9 @@ public abstract class AbstractDb implements Serializable {
* *
* @param where 条件 * @param where 条件
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Entity get(final Entity where) throws SQLException { public Entity get(final Entity where) throws DbRuntimeException {
return find(where.getFieldNames(), where, new EntityHandler(this.caseInsensitive)); return find(where.getFieldNames(), where, new EntityHandler(this.caseInsensitive));
} }
@ -510,13 +496,13 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T find(final Collection<String> fields, final Entity where, final RsHandler<T> rsh) throws SQLException { public <T> T find(final Collection<String> fields, final Entity where, final RsHandler<T> rsh) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.find(conn, fields, where, rsh); return runner.find(conn, Query.of(where).setFields(fields), rsh);
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -529,10 +515,10 @@ public abstract class AbstractDb implements Serializable {
* @param fields 返回的字段列表null则返回所有字段 * @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @return 结果Entity列表 * @return 结果Entity列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.5.16 * @since 4.5.16
*/ */
public List<Entity> find(final Collection<String> fields, final Entity where) throws SQLException { public List<Entity> find(final Collection<String> fields, final Entity where) throws DbRuntimeException {
return find(fields, where, new EntityListHandler(this.caseInsensitive)); return find(fields, where, new EntityListHandler(this.caseInsensitive));
} }
@ -544,10 +530,10 @@ public abstract class AbstractDb implements Serializable {
* @param query {@link Query}对象此对象中可以定义返回字段查询条件查询的表分页等信息 * @param query {@link Query}对象此对象中可以定义返回字段查询条件查询的表分页等信息
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.0 * @since 4.0.0
*/ */
public <T> T find(final Query query, final RsHandler<T> rsh) throws SQLException { public <T> T find(final Query query, final RsHandler<T> rsh) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -566,9 +552,9 @@ public abstract class AbstractDb implements Serializable {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param fields 字段列表可变长参数如果无值表示查询全部字段 * @param fields 字段列表可变长参数如果无值表示查询全部字段
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T find(final Entity where, final RsHandler<T> rsh, final String... fields) throws SQLException { public <T> T find(final Entity where, final RsHandler<T> rsh, final String... fields) throws DbRuntimeException {
return find(CollUtil.newArrayList(fields), where, rsh); return find(CollUtil.newArrayList(fields), where, rsh);
} }
@ -578,10 +564,10 @@ public abstract class AbstractDb implements Serializable {
* *
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.1 * @since 3.2.1
*/ */
public List<Entity> find(final Entity where) throws SQLException { public List<Entity> find(final Entity where) throws DbRuntimeException {
return find(where.getFieldNames(), where, new EntityListHandler(this.caseInsensitive)); return find(where.getFieldNames(), where, new EntityListHandler(this.caseInsensitive));
} }
@ -593,10 +579,10 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param beanClass Bean类 * @param beanClass Bean类
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public <T> List<T> find(final Entity where, final Class<T> beanClass) throws SQLException { public <T> List<T> find(final Entity where, final Class<T> beanClass) throws DbRuntimeException {
return find(where.getFieldNames(), where, BeanListHandler.create(beanClass)); return find(where.getFieldNames(), where, BeanListHandler.create(beanClass));
} }
@ -606,9 +592,9 @@ public abstract class AbstractDb implements Serializable {
* *
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findAll(final Entity where) throws SQLException { public List<Entity> findAll(final Entity where) throws DbRuntimeException {
return find(where, EntityListHandler.create()); return find(where, EntityListHandler.create());
} }
@ -620,10 +606,10 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param beanClass 返回的对象类型 * @param beanClass 返回的对象类型
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public <T> List<T> findAll(final Entity where, final Class<T> beanClass) throws SQLException { public <T> List<T> findAll(final Entity where, final Class<T> beanClass) throws DbRuntimeException {
return find(where, BeanListHandler.create(beanClass)); return find(where, BeanListHandler.create(beanClass));
} }
@ -632,9 +618,9 @@ public abstract class AbstractDb implements Serializable {
* *
* @param tableName 表名 * @param tableName 表名
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findAll(final String tableName) throws SQLException { public List<Entity> findAll(final String tableName) throws DbRuntimeException {
return findAll(Entity.create(tableName)); return findAll(Entity.create(tableName));
} }
@ -645,9 +631,9 @@ public abstract class AbstractDb implements Serializable {
* @param field 字段名 * @param field 字段名
* @param value 字段值 * @param value 字段值
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findBy(final String tableName, final String field, final Object value) throws SQLException { public List<Entity> findBy(final String tableName, final String field, final Object value) throws DbRuntimeException {
return findAll(Entity.create(tableName).set(field, value)); return findAll(Entity.create(tableName).set(field, value));
} }
@ -657,10 +643,10 @@ public abstract class AbstractDb implements Serializable {
* @param tableName 表名 * @param tableName 表名
* @param wheres 条件多个条件的连接逻辑使用{@link Condition#setLinkOperator(LogicalOperator)} 定义 * @param wheres 条件多个条件的连接逻辑使用{@link Condition#setLinkOperator(LogicalOperator)} 定义
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.0 * @since 4.0.0
*/ */
public List<Entity> findBy(final String tableName, final Condition... wheres) throws SQLException { public List<Entity> findBy(final String tableName, final Condition... wheres) throws DbRuntimeException {
final Query query = new Query(wheres, tableName); final Query query = new Query(wheres, tableName);
return find(query, new EntityListHandler(this.caseInsensitive)); return find(query, new EntityListHandler(this.caseInsensitive));
} }
@ -673,9 +659,9 @@ public abstract class AbstractDb implements Serializable {
* @param value 字段值 * @param value 字段值
* @param likeType {@link LikeType} * @param likeType {@link LikeType}
* @return 数据对象列表 * @return 数据对象列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findLike(final String tableName, final String field, final String value, final LikeType likeType) throws SQLException { public List<Entity> findLike(final String tableName, final String field, final String value, final LikeType likeType) throws DbRuntimeException {
return findAll(Entity.create(tableName).set(field, SqlUtil.buildLikeValue(value, likeType, true))); return findAll(Entity.create(tableName).set(field, SqlUtil.buildLikeValue(value, likeType, true)));
} }
@ -684,13 +670,13 @@ public abstract class AbstractDb implements Serializable {
* *
* @param where 查询条件 * @param where 查询条件
* @return 复合条件的结果数 * @return 复合条件的结果数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public long count(final Entity where) throws SQLException { public long count(final Entity where) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.count(conn, where); return runner.count(conn, Query.of(where));
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -701,9 +687,9 @@ public abstract class AbstractDb implements Serializable {
* *
* @param sql sql构造器 * @param sql sql构造器
* @return 复合条件的结果数 * @return 复合条件的结果数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public long count(final SqlBuilder sql) throws SQLException { public long count(final SqlBuilder sql) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -719,74 +705,19 @@ public abstract class AbstractDb implements Serializable {
* @param selectSql 查询SQL语句 * @param selectSql 查询SQL语句
* @param params 查询参数 * @param params 查询参数
* @return 复合条件的结果数 * @return 复合条件的结果数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.6.6 * @since 5.6.6
*/ */
public long count(final CharSequence selectSql, final Object... params) throws SQLException { public long count(final CharSequence selectSql, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.count(conn, selectSql, params); return runner.count(conn, SqlBuilder.of(selectSql).addParams(params));
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
} }
/**
* 分页查询<br>
* 查询条件为多个key value对表示默认key = value如果使用其它条件可以使用where.put("key", " &gt; 1")value也可以传Condition对象key被忽略
*
* @param <T> 结果对象类型
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param page 页码0表示第一页
* @param numPerPage 每页条目数
* @param rsh 结果集处理对象
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public <T> T page(final Collection<String> fields, final Entity where, final int page, final int numPerPage, final RsHandler<T> rsh) throws SQLException {
Connection conn = null;
try {
conn = this.getConnection();
return runner.page(conn, fields, where, page, numPerPage, rsh);
} finally {
this.closeConnection(conn);
}
}
/**
* 分页查询<br>
* 查询条件为多个key value对表示默认key = value如果使用其它条件可以使用where.put("key", " &gt; 1")value也可以传Condition对象key被忽略
*
* @param <T> 结果对象类型
* @param where 条件实体类包含表名
* @param page 页码0表示第一页
* @param numPerPage 每页条目数
* @param rsh 结果集处理对象
* @return 结果对象
* @throws SQLException SQL执行异常
* @since 3.2.2
*/
public <T> T page(final Entity where, final int page, final int numPerPage, final RsHandler<T> rsh) throws SQLException {
return page(where, new Page(page, numPerPage), rsh);
}
/**
* 分页查询结果为Entity列表不计算总数<br>
* 查询条件为多个key value对表示默认key = value如果使用其它条件可以使用where.put("key", " &gt; 1")value也可以传Condition对象key被忽略
*
* @param where 条件实体类包含表名
* @param page 页码0表示第一页
* @param numPerPage 每页条目数
* @return 结果对象
* @throws SQLException SQL执行异常
* @since 3.2.2
*/
public List<Entity> pageForEntityList(final Entity where, final int page, final int numPerPage) throws SQLException {
return pageForEntityList(where, new Page(page, numPerPage));
}
/** /**
* 分页查询结果为Entity列表不计算总数<br> * 分页查询结果为Entity列表不计算总数<br>
* 查询条件为多个key value对表示默认key = value如果使用其它条件可以使用where.put("key", " &gt; 1")value也可以传Condition对象key被忽略 * 查询条件为多个key value对表示默认key = value如果使用其它条件可以使用where.put("key", " &gt; 1")value也可以传Condition对象key被忽略
@ -794,10 +725,10 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param page 分页对象 * @param page 分页对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public List<Entity> pageForEntityList(final Entity where, final Page page) throws SQLException { public List<Entity> pageForEntityList(final Entity where, final Page page) throws DbRuntimeException {
return page(where, page, new EntityListHandler(this.caseInsensitive)); return page(where, page, new EntityListHandler(this.caseInsensitive));
} }
@ -810,10 +741,10 @@ public abstract class AbstractDb implements Serializable {
* @param page 分页对象 * @param page 分页对象
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public <T> T page(final Entity where, final Page page, final RsHandler<T> rsh) throws SQLException { public <T> T page(final Entity where, final Page page, final RsHandler<T> rsh) throws DbRuntimeException {
return page(where.getFieldNames(), where, page, rsh); return page(where.getFieldNames(), where, page, rsh);
} }
@ -827,13 +758,13 @@ public abstract class AbstractDb implements Serializable {
* @param page 分页对象 * @param page 分页对象
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T page(final Collection<String> fields, final Entity where, final Page page, final RsHandler<T> rsh) throws SQLException { public <T> T page(final Collection<String> fields, final Entity where, final Page page, final RsHandler<T> rsh) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.page(conn, fields, where, page, rsh); return runner.page(conn, Query.of(where).setFields(fields).setPage(page), rsh);
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -848,10 +779,10 @@ public abstract class AbstractDb implements Serializable {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.6.6 * @since 5.6.6
*/ */
public <T> T page(final CharSequence sql, final Page page, final RsHandler<T> rsh, final Object... params) throws SQLException { public <T> T page(final CharSequence sql, final Page page, final RsHandler<T> rsh, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -869,9 +800,9 @@ public abstract class AbstractDb implements Serializable {
* @param page 分页对象 * @param page 分页对象
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T page(final SqlBuilder sql, final Page page, final RsHandler<T> rsh) throws SQLException { public <T> T page(final SqlBuilder sql, final Page page, final RsHandler<T> rsh) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -888,10 +819,10 @@ public abstract class AbstractDb implements Serializable {
* @param page 分页对象 * @param page 分页对象
* @param params 参数列表 * @param params 参数列表
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.5.3 * @since 5.5.3
*/ */
public PageResult<Entity> page(final CharSequence sql, final Page page, final Object... params) throws SQLException { public PageResult<Entity> page(final CharSequence sql, final Page page, final Object... params) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
@ -910,9 +841,9 @@ public abstract class AbstractDb implements Serializable {
* @param pageNumber 页码 * @param pageNumber 页码
* @param pageSize 每页结果数 * @param pageSize 每页结果数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public PageResult<Entity> page(final Collection<String> fields, final Entity where, final int pageNumber, final int pageSize) throws SQLException { public PageResult<Entity> page(final Collection<String> fields, final Entity where, final int pageNumber, final int pageSize) throws DbRuntimeException {
return page(fields, where, new Page(pageNumber, pageSize)); return page(fields, where, new Page(pageNumber, pageSize));
} }
@ -924,13 +855,13 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param page 分页对象 * @param page 分页对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public PageResult<Entity> page(final Collection<String> fields, final Entity where, final Page page) throws SQLException { public PageResult<Entity> page(final Collection<String> fields, final Entity where, final Page page) throws DbRuntimeException {
Connection conn = null; Connection conn = null;
try { try {
conn = this.getConnection(); conn = this.getConnection();
return runner.page(conn, fields, where, page); return runner.page(conn, Query.of(where).setFields(fields).setPage(page));
} finally { } finally {
this.closeConnection(conn); this.closeConnection(conn);
} }
@ -944,10 +875,10 @@ public abstract class AbstractDb implements Serializable {
* @param page 页码 * @param page 页码
* @param numPerPage 每页条目数 * @param numPerPage 每页条目数
* @return 分页结果集 * @return 分页结果集
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 3.2.2 * @since 3.2.2
*/ */
public PageResult<Entity> page(final Entity where, final int page, final int numPerPage) throws SQLException { public PageResult<Entity> page(final Entity where, final int page, final int numPerPage) throws DbRuntimeException {
return this.page(where, new Page(page, numPerPage)); return this.page(where, new Page(page, numPerPage));
} }
@ -958,9 +889,9 @@ public abstract class AbstractDb implements Serializable {
* @param where 条件实体类包含表名 * @param where 条件实体类包含表名
* @param page 分页对象 * @param page 分页对象
* @return 分页结果集 * @return 分页结果集
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public PageResult<Entity> page(final Entity where, final Page page) throws SQLException { public PageResult<Entity> page(final Entity where, final Page page) throws DbRuntimeException {
return this.page(where.getFieldNames(), where, page); return this.page(where.getFieldNames(), where, page);
} }
// ---------------------------------------------------------------------------- CRUD end // ---------------------------------------------------------------------------- CRUD end
@ -974,26 +905,30 @@ public abstract class AbstractDb implements Serializable {
* @param caseInsensitive 否在结果中忽略大小写 * @param caseInsensitive 否在结果中忽略大小写
* @since 5.2.4 * @since 5.2.4
*/ */
public void setCaseInsensitive(final boolean caseInsensitive) { @SuppressWarnings("unchecked")
public R setCaseInsensitive(final boolean caseInsensitive) {
this.caseInsensitive = caseInsensitive; this.caseInsensitive = caseInsensitive;
return (R) this;
} }
/** /**
* 获取{@link SqlConnRunner} * 获取{@link DialectRunner}
* *
* @return {@link SqlConnRunner} * @return {@link DialectRunner}
*/ */
public SqlConnRunner getRunner() { public DialectRunner getRunner() {
return runner; return runner;
} }
/** /**
* 设置 {@link SqlConnRunner} * 设置 {@link DialectRunner}
* *
* @param runner {@link SqlConnRunner} * @param runner {@link DialectRunner}
*/ */
public void setRunner(final SqlConnRunner runner) { @SuppressWarnings("unchecked")
public R setRunner(final DialectRunner runner) {
this.runner = runner; this.runner = runner;
return (R) this;
} }
/** /**
@ -1003,7 +938,7 @@ public abstract class AbstractDb implements Serializable {
* @return this * @return this
* @since 4.0.0 * @since 4.0.0
*/ */
public AbstractDb setWrapper(final Character wrapperChar) { public R setWrapper(final Character wrapperChar) {
return setWrapper(new Wrapper(wrapperChar)); return setWrapper(new Wrapper(wrapperChar));
} }
@ -1014,9 +949,10 @@ public abstract class AbstractDb implements Serializable {
* @return this * @return this
* @since 4.0.0 * @since 4.0.0
*/ */
public AbstractDb setWrapper(final Wrapper wrapper) { @SuppressWarnings("unchecked")
public R setWrapper(final Wrapper wrapper) {
this.runner.setWrapper(wrapper); this.runner.setWrapper(wrapper);
return this; return (R) this;
} }
/** /**
@ -1026,7 +962,7 @@ public abstract class AbstractDb implements Serializable {
* @return this * @return this
* @since 4.5.7 * @since 4.5.7
*/ */
public AbstractDb disableWrapper() { public R disableWrapper() {
return setWrapper((Wrapper) null); return setWrapper((Wrapper) null);
} }
// ---------------------------------------------------------------------------- Getters and Setters end // ---------------------------------------------------------------------------- Getters and Setters end
@ -1037,12 +973,16 @@ public abstract class AbstractDb implements Serializable {
* 检查数据库是否支持事务此项检查同一个数据源只检查一次如果不支持抛出DbRuntimeException异常 * 检查数据库是否支持事务此项检查同一个数据源只检查一次如果不支持抛出DbRuntimeException异常
* *
* @param conn Connection * @param conn Connection
* @throws SQLException 获取元数据信息失败 * @throws DbRuntimeException 获取元数据信息失败
* @throws DbRuntimeException 不支持事务 * @throws DbRuntimeException 不支持事务
*/ */
protected void checkTransactionSupported(final Connection conn) throws SQLException, DbRuntimeException { protected void checkTransactionSupported(final Connection conn) throws DbRuntimeException {
if (null == isSupportTransaction) { if (null == isSupportTransaction) {
try {
isSupportTransaction = conn.getMetaData().supportsTransactions(); isSupportTransaction = conn.getMetaData().supportsTransactions();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
if (false == isSupportTransaction) { if (false == isSupportTransaction) {
throw new DbRuntimeException("Transaction not supported for current database!"); throw new DbRuntimeException("Transaction not supported for current database!");

View File

@ -1,11 +1,10 @@
package cn.hutool.db; package cn.hutool.db;
import java.sql.SQLException;
import java.util.Collection;
import cn.hutool.core.lang.func.Func0; import cn.hutool.core.lang.func.Func0;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import java.util.Collection;
/** /**
* 动态实体类<br> * 动态实体类<br>
* 提供了针对自身实体的增删改方法 * 提供了针对自身实体的增删改方法
@ -79,7 +78,7 @@ public class ActiveEntity extends Entity {
* 构造 * 构造
*/ */
public ActiveEntity() { public ActiveEntity() {
this(Db.use(), (String) null); this(Db.of(), (String) null);
} }
/** /**
@ -88,7 +87,7 @@ public class ActiveEntity extends Entity {
* @param tableName 表名 * @param tableName 表名
*/ */
public ActiveEntity(final String tableName) { public ActiveEntity(final String tableName) {
this(Db.use(), tableName); this(Db.of(), tableName);
} }
/** /**
@ -97,7 +96,7 @@ public class ActiveEntity extends Entity {
* @param entity 非动态实体 * @param entity 非动态实体
*/ */
public ActiveEntity(final Entity entity) { public ActiveEntity(final Entity entity) {
this(Db.use(), entity); this(Db.of(), entity);
} }
/** /**
@ -186,11 +185,7 @@ public class ActiveEntity extends Entity {
* @return this * @return this
*/ */
public ActiveEntity add() { public ActiveEntity add() {
try {
db.insert(this); db.insert(this);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
return this; return this;
} }
@ -200,14 +195,10 @@ public class ActiveEntity extends Entity {
* @return this * @return this
*/ */
public ActiveEntity load() { public ActiveEntity load() {
try {
final Entity result = db.get(this); final Entity result = db.get(this);
if(MapUtil.isNotEmpty(result)) { if(MapUtil.isNotEmpty(result)) {
this.putAll(result); this.putAll(result);
} }
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
return this; return this;
} }
@ -217,11 +208,7 @@ public class ActiveEntity extends Entity {
* @return this * @return this
*/ */
public ActiveEntity del() { public ActiveEntity del() {
try {
db.del(this); db.del(this);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
return this; return this;
} }
@ -232,11 +219,7 @@ public class ActiveEntity extends Entity {
* @return this * @return this
*/ */
public ActiveEntity update(final String primaryKey) { public ActiveEntity update(final String primaryKey) {
try {
db.update(this, Entity.create().set(primaryKey, this.get(primaryKey))); db.update(this, Entity.create().set(primaryKey, this.get(primaryKey)));
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
return this; return this;
} }
// -------------------------------------------------------------------------- CRUD end // -------------------------------------------------------------------------- CRUD end

View File

@ -0,0 +1,27 @@
package cn.hutool.db;
import java.sql.Connection;
/**
* 控制{@link Connection}获取和关闭
*
* @author looly
* @since 6.0.0
*/
public interface ConnectionHolder {
/**
* 获得链接根据实现不同可以自定义获取连接的方式
*
* @return {@link Connection}
* @throws DbRuntimeException 连接获取异常
*/
Connection getConnection() throws DbRuntimeException;
/**
* 关闭连接<br>
* 自定义关闭连接有利于自定义回收连接机制或者不关闭
*
* @param conn 连接 {@link Connection}
*/
void closeConnection(Connection conn);
}

View File

@ -5,7 +5,6 @@ import cn.hutool.core.text.StrUtil;
import cn.hutool.db.ds.DSFactory; import cn.hutool.db.ds.DSFactory;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -71,7 +70,7 @@ public class DaoTemplate {
* @param ds 数据源 * @param ds 数据源
*/ */
public DaoTemplate(final String tableName, final String primaryKeyField, final DataSource ds) { public DaoTemplate(final String tableName, final String primaryKeyField, final DataSource ds) {
this(tableName, primaryKeyField, Db.use(ds)); this(tableName, primaryKeyField, Db.of(ds));
} }
/** /**
@ -97,9 +96,9 @@ public class DaoTemplate {
* *
* @param entity 实体对象 * @param entity 实体对象
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int add(final Entity entity) throws SQLException { public int add(final Entity entity) throws DbRuntimeException {
return db.insert(fixEntity(entity)); return db.insert(fixEntity(entity));
} }
@ -108,9 +107,9 @@ public class DaoTemplate {
* *
* @param entity 实体对象 * @param entity 实体对象
* @return 主键列表 * @return 主键列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Object> addForGeneratedKeys(final Entity entity) throws SQLException { public List<Object> addForGeneratedKeys(final Entity entity) throws DbRuntimeException {
return db.insertForGeneratedKeys(fixEntity(entity)); return db.insertForGeneratedKeys(fixEntity(entity));
} }
@ -119,9 +118,9 @@ public class DaoTemplate {
* *
* @param entity 实体对象 * @param entity 实体对象
* @return 自增主键 * @return 自增主键
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Long addForGeneratedKey(final Entity entity) throws SQLException { public Long addForGeneratedKey(final Entity entity) throws DbRuntimeException {
return db.insertForGeneratedKey(fixEntity(entity)); return db.insertForGeneratedKey(fixEntity(entity));
} }
//------------------------------------------------------------- Add end //------------------------------------------------------------- Add end
@ -134,9 +133,9 @@ public class DaoTemplate {
* @param <T> 主键类型 * @param <T> 主键类型
* @param pk 主键 * @param pk 主键
* @return 删除行数 * @return 删除行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> int del(final T pk) throws SQLException { public <T> int del(final T pk) throws DbRuntimeException {
if (pk == null) { if (pk == null) {
return 0; return 0;
} }
@ -150,9 +149,9 @@ public class DaoTemplate {
* @param field 字段名 * @param field 字段名
* @param value 字段值 * @param value 字段值
* @return 删除行数 * @return 删除行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> int del(final String field, final T value) throws SQLException { public <T> int del(final String field, final T value) throws DbRuntimeException {
if (StrUtil.isBlank(field)) { if (StrUtil.isBlank(field)) {
return 0; return 0;
} }
@ -163,12 +162,11 @@ public class DaoTemplate {
/** /**
* 删除 * 删除
* *
* @param <T> 主键类型
* @param where 删除条件当条件为空时返回0防止误删全表 * @param where 删除条件当条件为空时返回0防止误删全表
* @return 删除行数 * @return 删除行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> int del(final Entity where) throws SQLException { public int del(final Entity where) throws DbRuntimeException {
if (MapUtil.isEmpty(where)) { if (MapUtil.isEmpty(where)) {
return 0; return 0;
} }
@ -184,9 +182,9 @@ public class DaoTemplate {
* @param record 更新的内容 * @param record 更新的内容
* @param where 条件 * @param where 条件
* @return 更新条目数 * @return 更新条目数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int update(final Entity record, final Entity where) throws SQLException { public int update(final Entity record, final Entity where) throws DbRuntimeException {
if (MapUtil.isEmpty(record)) { if (MapUtil.isEmpty(record)) {
return 0; return 0;
} }
@ -198,16 +196,16 @@ public class DaoTemplate {
* *
* @param entity 实体对象必须包含主键 * @param entity 实体对象必须包含主键
* @return 更新行数 * @return 更新行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int update(Entity entity) throws SQLException { public int update(Entity entity) throws DbRuntimeException {
if (MapUtil.isEmpty(entity)) { if (MapUtil.isEmpty(entity)) {
return 0; return 0;
} }
entity = fixEntity(entity); entity = fixEntity(entity);
final Object pk = entity.get(primaryKeyField); final Object pk = entity.get(primaryKeyField);
if (null == pk) { if (null == pk) {
throw new SQLException(StrUtil.format("Please determine `{}` for update", primaryKeyField)); throw new DbRuntimeException(StrUtil.format("Please determine `{}` for update", primaryKeyField));
} }
final Entity where = Entity.create(tableName).set(primaryKeyField, pk); final Entity where = Entity.create(tableName).set(primaryKeyField, pk);
@ -222,9 +220,9 @@ public class DaoTemplate {
* *
* @param entity 实体当包含主键时更新否则新增 * @param entity 实体当包含主键时更新否则新增
* @return 新增或更新条数 * @return 新增或更新条数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int addOrUpdate(final Entity entity) throws SQLException { public int addOrUpdate(final Entity entity) throws DbRuntimeException {
return null == entity.get(primaryKeyField) ? add(entity) : update(entity); return null == entity.get(primaryKeyField) ? add(entity) : update(entity);
} }
//------------------------------------------------------------- Update end //------------------------------------------------------------- Update end
@ -237,9 +235,9 @@ public class DaoTemplate {
* @param <T> 主键类型 * @param <T> 主键类型
* @param pk 主键值 * @param pk 主键值
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> Entity get(final T pk) throws SQLException { public <T> Entity get(final T pk) throws DbRuntimeException {
return this.get(primaryKeyField, pk); return this.get(primaryKeyField, pk);
} }
@ -251,9 +249,9 @@ public class DaoTemplate {
* @param field 字段名 * @param field 字段名
* @param value 字段值 * @param value 字段值
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> Entity get(final String field, final T value) throws SQLException { public <T> Entity get(final String field, final T value) throws DbRuntimeException {
return this.get(Entity.create(tableName).set(field, value)); return this.get(Entity.create(tableName).set(field, value));
} }
@ -262,9 +260,9 @@ public class DaoTemplate {
* *
* @param where 条件 * @param where 条件
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Entity get(final Entity where) throws SQLException { public Entity get(final Entity where) throws DbRuntimeException {
return db.get(fixEntity(where)); return db.get(fixEntity(where));
} }
//------------------------------------------------------------- Get end //------------------------------------------------------------- Get end
@ -278,9 +276,9 @@ public class DaoTemplate {
* @param field 字段名 * @param field 字段名
* @param value 字段值 * @param value 字段值
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> List<Entity> find(final String field, final T value) throws SQLException { public <T> List<Entity> find(final String field, final T value) throws DbRuntimeException {
return this.find(Entity.create(tableName).set(field, value)); return this.find(Entity.create(tableName).set(field, value));
} }
@ -288,9 +286,9 @@ public class DaoTemplate {
* 查询当前表的所有记录 * 查询当前表的所有记录
* *
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findAll() throws SQLException { public List<Entity> findAll() throws DbRuntimeException {
return this.find(Entity.create(tableName)); return this.find(Entity.create(tableName));
} }
@ -299,9 +297,9 @@ public class DaoTemplate {
* *
* @param where 查询条件 * @param where 查询条件
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> find(final Entity where) throws SQLException { public List<Entity> find(final Entity where) throws DbRuntimeException {
return db.find(null, fixEntity(where)); return db.find(null, fixEntity(where));
} }
@ -313,9 +311,9 @@ public class DaoTemplate {
* @param sql SQL语句 * @param sql SQL语句
* @param params SQL占位符中对应的参数 * @param params SQL占位符中对应的参数
* @return 记录 * @return 记录
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public List<Entity> findBySql(String sql, final Object... params) throws SQLException { public List<Entity> findBySql(String sql, final Object... params) throws DbRuntimeException {
final String selectKeyword = StrUtil.subPre(sql.trim(), 6).toLowerCase(); final String selectKeyword = StrUtil.subPre(sql.trim(), 6).toLowerCase();
if (false == "select".equals(selectKeyword)) { if (false == "select".equals(selectKeyword)) {
sql = "SELECT * FROM " + this.tableName + " " + sql; sql = "SELECT * FROM " + this.tableName + " " + sql;
@ -330,9 +328,9 @@ public class DaoTemplate {
* @param page 分页对象 * @param page 分页对象
* @param selectFields 查询的字段列表 * @param selectFields 查询的字段列表
* @return 分页结果集 * @return 分页结果集
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public PageResult<Entity> page(final Entity where, final Page page, final String... selectFields) throws SQLException { public PageResult<Entity> page(final Entity where, final Page page, final String... selectFields) throws DbRuntimeException {
return db.page(Arrays.asList(selectFields), fixEntity(where), page); return db.page(Arrays.asList(selectFields), fixEntity(where), page);
} }
@ -342,9 +340,9 @@ public class DaoTemplate {
* @param where 条件 * @param where 条件
* @param page 分页对象 * @param page 分页对象
* @return 分页结果集 * @return 分页结果集
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public PageResult<Entity> page(final Entity where, final Page page) throws SQLException { public PageResult<Entity> page(final Entity where, final Page page) throws DbRuntimeException {
return db.page(fixEntity(where), page); return db.page(fixEntity(where), page);
} }
@ -353,9 +351,9 @@ public class DaoTemplate {
* *
* @param where 条件 * @param where 条件
* @return 数量 * @return 数量
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public long count(final Entity where) throws SQLException { public long count(final Entity where) throws DbRuntimeException {
return db.count(fixEntity(where)); return db.count(fixEntity(where));
} }
@ -364,9 +362,9 @@ public class DaoTemplate {
* *
* @param where 条件 * @param where 条件
* @return 是否存在 * @return 是否存在
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public boolean exist(final Entity where) throws SQLException { public boolean exist(final Entity where) throws DbRuntimeException {
return this.count(where) > 0; return this.count(where) > 0;
} }
//------------------------------------------------------------- Find end //------------------------------------------------------------- Find end

View File

@ -4,7 +4,6 @@ import cn.hutool.core.lang.func.VoidFunc1;
import cn.hutool.db.dialect.Dialect; import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory; import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.ds.DSFactory; import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.db.transaction.TransactionLevel; import cn.hutool.db.transaction.TransactionLevel;
import cn.hutool.log.StaticLog; import cn.hutool.log.StaticLog;
@ -19,7 +18,7 @@ import java.sql.SQLException;
* @author Looly * @author Looly
* @since 4.1.2 * @since 4.1.2
*/ */
public class Db extends AbstractDb { public class Db extends AbstractDb<Db> {
private static final long serialVersionUID = -3378415769645309514L; private static final long serialVersionUID = -3378415769645309514L;
/** /**
@ -28,8 +27,8 @@ public class Db extends AbstractDb {
* *
* @return Db * @return Db
*/ */
public static Db use() { public static Db of() {
return use(DSFactory.get()); return of(DSFactory.get());
} }
/** /**
@ -39,8 +38,8 @@ public class Db extends AbstractDb {
* @param group 数据源分组 * @param group 数据源分组
* @return Db * @return Db
*/ */
public static Db use(final String group) { public static Db of(final String group) {
return use(DSFactory.get(group)); return of(DSFactory.get(group));
} }
/** /**
@ -50,7 +49,7 @@ public class Db extends AbstractDb {
* @param ds 数据源 * @param ds 数据源
* @return Db * @return Db
*/ */
public static Db use(final DataSource ds) { public static Db of(final DataSource ds) {
return ds == null ? null : new Db(ds); return ds == null ? null : new Db(ds);
} }
@ -61,7 +60,7 @@ public class Db extends AbstractDb {
* @param dialect 方言 * @param dialect 方言
* @return Db * @return Db
*/ */
public static Db use(final DataSource ds, final Dialect dialect) { public static Db of(final DataSource ds, final Dialect dialect) {
return new Db(ds, dialect); return new Db(ds, dialect);
} }
@ -72,7 +71,7 @@ public class Db extends AbstractDb {
* @param driverClassName 数据库连接驱动类名 * @param driverClassName 数据库连接驱动类名
* @return Db * @return Db
*/ */
public static Db use(final DataSource ds, final String driverClassName) { public static Db of(final DataSource ds, final String driverClassName) {
return new Db(ds, DialectFactory.newDialect(driverClassName)); return new Db(ds, DialectFactory.newDialect(driverClassName));
} }
@ -107,26 +106,13 @@ public class Db extends AbstractDb {
} }
// ---------------------------------------------------------------------------- Constructor end // ---------------------------------------------------------------------------- Constructor end
// ---------------------------------------------------------------------------- Getters and Setters start
@Override @Override
public Db setWrapper(final Character wrapperChar) { public Connection getConnection() throws DbRuntimeException {
return (Db) super.setWrapper(wrapperChar); try {
}
@Override
public Db setWrapper(final Wrapper wrapper) {
return (Db) super.setWrapper(wrapper);
}
@Override
public Db disableWrapper() {
return (Db)super.disableWrapper();
}
// ---------------------------------------------------------------------------- Getters and Setters end
@Override
public Connection getConnection() throws SQLException {
return ThreadLocalConnection.INSTANCE.get(this.ds); return ThreadLocalConnection.INSTANCE.get(this.ds);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
@Override @Override

View File

@ -5,9 +5,10 @@ import cn.hutool.core.text.StrUtil;
/** /**
* 数据库异常 * 数据库异常
*
* @author xiaoleilu * @author xiaoleilu
*/ */
public class DbRuntimeException extends RuntimeException{ public class DbRuntimeException extends RuntimeException {
private static final long serialVersionUID = 3624487785708765623L; private static final long serialVersionUID = 3624487785708765623L;
public DbRuntimeException(final Throwable e) { public DbRuntimeException(final Throwable e) {

View File

@ -2,8 +2,6 @@ package cn.hutool.db;
import cn.hutool.core.convert.Convert; import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil; import cn.hutool.core.io.IoUtil;
import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.ds.DSFactory; import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.sql.SqlLog; import cn.hutool.db.sql.SqlLog;
import cn.hutool.log.Log; import cn.hutool.log.Log;
@ -13,7 +11,6 @@ import cn.hutool.setting.Setting;
import javax.naming.InitialContext; import javax.naming.InitialContext;
import javax.naming.NamingException; import javax.naming.NamingException;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.Connection;
/** /**
* 数据库操作工具类 * 数据库操作工具类
@ -23,85 +20,6 @@ import java.sql.Connection;
public final class DbUtil { public final class DbUtil {
private final static Log log = Log.get(); private final static Log log = Log.get();
/**
* 实例化一个新的SQL运行对象
*
* @param dialect 数据源
* @return SQL执行类
*/
public static SqlConnRunner newSqlConnRunner(final Dialect dialect) {
return SqlConnRunner.create(dialect);
}
/**
* 实例化一个新的SQL运行对象
*
* @param ds 数据源
* @return SQL执行类
*/
public static SqlConnRunner newSqlConnRunner(final DataSource ds) {
return SqlConnRunner.create(ds);
}
/**
* 实例化一个新的SQL运行对象
*
* @param conn 数据库连接对象
* @return SQL执行类
*/
public static SqlConnRunner newSqlConnRunner(final Connection conn) {
return SqlConnRunner.create(DialectFactory.newDialect(conn));
}
/**
* 实例化一个新的Db使用默认数据源
*
* @return SQL执行类
*/
public static Db use() {
return Db.use();
}
/**
* 实例化一个新的Db对象
*
* @param ds 数据源
* @return SQL执行类
*/
public static Db use(final DataSource ds) {
return Db.use(ds);
}
/**
* 实例化一个新的SQL运行对象
*
* @param ds 数据源
* @param dialect SQL方言
* @return SQL执行类
*/
public static Db use(final DataSource ds, final Dialect dialect) {
return Db.use(ds, dialect);
}
/**
* 新建数据库会话使用默认数据源
*
* @return 数据库会话
*/
public static Session newSession() {
return Session.create(getDs());
}
/**
* 新建数据库会话
*
* @param ds 数据源
* @return 数据库会话
*/
public static Session newSession(final DataSource ds) {
return Session.create(ds);
}
/** /**
* 连续关闭一系列的SQL相关对象<br> * 连续关闭一系列的SQL相关对象<br>
* 这些对象必须按照顺序关闭否则会出错 * 这些对象必须按照顺序关闭否则会出错

View File

@ -2,11 +2,12 @@ package cn.hutool.db;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.db.dialect.Dialect; import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory; import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.handler.NumberHandler; import cn.hutool.db.handler.NumberHandler;
import cn.hutool.db.handler.PageResultHandler;
import cn.hutool.db.handler.RsHandler; import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.Query; import cn.hutool.db.sql.Query;
import cn.hutool.db.sql.SqlBuilder; import cn.hutool.db.sql.SqlBuilder;
@ -62,9 +63,9 @@ public class DialectRunner implements Serializable {
* @param conn 数据库连接 * @param conn 数据库连接
* @param records 记录列表记录KV必须严格一致 * @param records 记录列表记录KV必须严格一致
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int[] insert(final Connection conn, final Entity... records) throws SQLException { public int[] insert(final Connection conn, final Entity... records) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (ArrayUtil.isEmpty(records)) { if (ArrayUtil.isEmpty(records)) {
return new int[]{0}; return new int[]{0};
@ -81,6 +82,8 @@ public class DialectRunner implements Serializable {
// 批量 // 批量
ps = dialect.psForInsertBatch(conn, records); ps = dialect.psForInsertBatch(conn, records);
return ps.executeBatch(); return ps.executeBatch();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -95,19 +98,21 @@ public class DialectRunner implements Serializable {
* @param record 记录 * @param record 记录
* @param keys 需要检查唯一性的字段 * @param keys 需要检查唯一性的字段
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.7.20 * @since 5.7.20
*/ */
public int upsert(final Connection conn, final Entity record, final String... keys) throws SQLException { public int upsert(final Connection conn, final Entity record, final String... keys) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
try{ try {
ps = getDialect().psForUpsert(conn, record, keys); ps = getDialect().psForUpsert(conn, record, keys);
}catch (final SQLException ignore){ } catch (final SQLException ignore) {
// 方言不支持使用默认 // 方言不支持使用默认
} }
if (null != ps) { if (null != ps) {
try { try {
return ps.executeUpdate(); return ps.executeUpdate();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -124,11 +129,11 @@ public class DialectRunner implements Serializable {
* @param record 记录 * @param record 记录
* @param keys 需要检查唯一性的字段 * @param keys 需要检查唯一性的字段
* @return 插入行数 * @return 插入行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int insertOrUpdate(final Connection conn, final Entity record, final String... keys) throws SQLException { public int insertOrUpdate(final Connection conn, final Entity record, final String... keys) throws DbRuntimeException {
final Entity where = record.filter(keys); final Entity where = record.filter(keys);
if (MapUtil.isNotEmpty(where) && count(conn, where) > 0) { if (MapUtil.isNotEmpty(where) && count(conn, Query.of(where)) > 0) {
return update(conn, record, where); return update(conn, record, where);
} else { } else {
return insert(conn, record)[0]; return insert(conn, record)[0];
@ -144,12 +149,12 @@ public class DialectRunner implements Serializable {
* @param record 记录 * @param record 记录
* @param generatedKeysHandler 自增主键处理器用于定义返回自增主键的范围和类型 * @param generatedKeysHandler 自增主键处理器用于定义返回自增主键的范围和类型
* @return 主键列表 * @return 主键列表
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T insert(final Connection conn, final Entity record, final RsHandler<T> generatedKeysHandler) throws SQLException { public <T> T insert(final Connection conn, final Entity record, final RsHandler<T> generatedKeysHandler) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (MapUtil.isEmpty(record)) { if (MapUtil.isEmpty(record)) {
throw new SQLException("Empty entity provided!"); throw new DbRuntimeException("Empty entity provided!");
} }
PreparedStatement ps = null; PreparedStatement ps = null;
@ -160,6 +165,8 @@ public class DialectRunner implements Serializable {
return null; return null;
} }
return StatementUtil.getGeneratedKeys(ps, generatedKeysHandler); return StatementUtil.getGeneratedKeys(ps, generatedKeysHandler);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -172,19 +179,21 @@ public class DialectRunner implements Serializable {
* @param conn 数据库连接 * @param conn 数据库连接
* @param where 条件 * @param where 条件
* @return 影响行数 * @return 影响行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int del(final Connection conn, final Entity where) throws SQLException { public int del(final Connection conn, final Entity where) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (MapUtil.isEmpty(where)) { if (MapUtil.isEmpty(where)) {
//不允许做全表删除 //不允许做全表删除
throw new SQLException("Empty entity provided!"); throw new DbRuntimeException("Empty entity provided!");
} }
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = dialect.psForDelete(conn, Query.of(where)); ps = dialect.psForDelete(conn, Query.of(where));
return ps.executeUpdate(); return ps.executeUpdate();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -198,16 +207,16 @@ public class DialectRunner implements Serializable {
* @param record 记录 * @param record 记录
* @param where 条件 * @param where 条件
* @return 影响行数 * @return 影响行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public int update(final Connection conn, final Entity record, final Entity where) throws SQLException { public int update(final Connection conn, final Entity record, final Entity where) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (MapUtil.isEmpty(record)) { if (MapUtil.isEmpty(record)) {
throw new SQLException("Empty entity provided!"); throw new DbRuntimeException("Empty entity provided!");
} }
if (MapUtil.isEmpty(where)) { if (MapUtil.isEmpty(where)) {
//不允许做全表更新 //不允许做全表更新
throw new SQLException("Empty where provided!"); throw new DbRuntimeException("Empty where provided!");
} }
//表名可以从被更新记录的Entity中获得也可以从Where中获得 //表名可以从被更新记录的Entity中获得也可以从Where中获得
@ -222,6 +231,8 @@ public class DialectRunner implements Serializable {
try { try {
ps = dialect.psForUpdate(conn, record, query); ps = dialect.psForUpdate(conn, record, query);
return ps.executeUpdate(); return ps.executeUpdate();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -236,25 +247,33 @@ public class DialectRunner implements Serializable {
* @param query {@link Query} * @param query {@link Query}
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T find(final Connection conn, final Query query, final RsHandler<T> rsh) throws SQLException { public <T> T find(final Connection conn, final Query query, final RsHandler<T> rsh) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
Assert.notNull(query, "[query] is null !"); Assert.notNull(query, "[query] is null !");
try {
return SqlExecutor.queryAndClosePs(dialect.psForFind(conn, query), rsh); return SqlExecutor.queryAndClosePs(dialect.psForFind(conn, query), rsh);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
* 获取结果总数生成类似于select count(1) from XXX wher XXX=? and YYY=? * 获取结果总数生成类似于select count(1) from XXX wher XXX=? and YYY=?
* *
* @param conn 数据库连接对象 * @param conn 数据库连接对象
* @param where 查询条件 * @param query 查询
* @return 复合条件的结果数 * @return 复合条件的结果数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public long count(final Connection conn, final Entity where) throws SQLException { public long count(final Connection conn, final Query query) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
return SqlExecutor.queryAndClosePs(dialect.psForCount(conn, Query.of(where)), new NumberHandler()).longValue(); try {
return SqlExecutor.queryAndClosePs(dialect.psForCount(conn, query), new NumberHandler()).longValue();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -264,10 +283,10 @@ public class DialectRunner implements Serializable {
* @param conn 数据库连接对象 * @param conn 数据库连接对象
* @param sqlBuilder 查询语句 * @param sqlBuilder 查询语句
* @return 复合条件的结果数 * @return 复合条件的结果数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.7.2 * @since 5.7.2
*/ */
public long count(final Connection conn, final SqlBuilder sqlBuilder) throws SQLException { public long count(final Connection conn, final SqlBuilder sqlBuilder) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
String selectSql = sqlBuilder.build(); String selectSql = sqlBuilder.build();
@ -276,9 +295,30 @@ public class DialectRunner implements Serializable {
if (orderByIndex > 0) { if (orderByIndex > 0) {
selectSql = StrUtil.subPre(selectSql, orderByIndex); selectSql = StrUtil.subPre(selectSql, orderByIndex);
} }
try {
return SqlExecutor.queryAndClosePs(dialect.psForCount(conn, return SqlExecutor.queryAndClosePs(dialect.psForCount(conn,
SqlBuilder.of(selectSql).addParams(sqlBuilder.getParamValueArray())), SqlBuilder.of(selectSql).addParams(sqlBuilder.getParamValueArray())),
new NumberHandler()).longValue(); new NumberHandler()).longValue();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param query 查询
* @return 结果对象
* @throws DbRuntimeException SQL执行异常
*/
public PageResult<Entity> page(final Connection conn, final Query query) throws DbRuntimeException {
final Page page = query.getPage();
final PageResultHandler pageResultHandler = new PageResultHandler(
new PageResult<>(page.getPageNumber(), page.getPageSize(), (int) count(conn, query)),
this.caseInsensitive);
return page(conn, query, pageResultHandler);
} }
/** /**
@ -290,15 +330,36 @@ public class DialectRunner implements Serializable {
* @param query 查询条件包含表名 * @param query 查询条件包含表名
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public <T> T page(final Connection conn, final Query query, final RsHandler<T> rsh) throws SQLException { public <T> T page(final Connection conn, final Query query, final RsHandler<T> rsh) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (null == query.getPage()) { if (null == query.getPage()) {
return this.find(conn, query, rsh); return this.find(conn, query, rsh);
} }
try {
return SqlExecutor.queryAndClosePs(dialect.psForPage(conn, query), rsh); return SqlExecutor.queryAndClosePs(dialect.psForPage(conn, query), rsh);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param sqlBuilder SQL构建器可以使用{@link SqlBuilder#of(CharSequence)} 包装普通SQL
* @param page 分页对象
* @return 结果对象
* @throws DbRuntimeException SQL执行异常
*/
public PageResult<Entity> page(final Connection conn, final SqlBuilder sqlBuilder, final Page page) throws DbRuntimeException {
final PageResultHandler pageResultHandler = new PageResultHandler(
new PageResult<>(page.getPageNumber(), page.getPageSize(), (int) count(conn, sqlBuilder)),
this.caseInsensitive);
return page(conn, sqlBuilder, page, pageResultHandler);
} }
/** /**
@ -311,16 +372,22 @@ public class DialectRunner implements Serializable {
* @param page 分页对象 * @param page 分页对象
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.5.3 * @since 5.5.3
*/ */
public <T> T page(final Connection conn, final SqlBuilder sqlBuilder, final Page page, final RsHandler<T> rsh) throws SQLException { public <T> T page(final Connection conn, final SqlBuilder sqlBuilder, final Page page, final RsHandler<T> rsh) throws DbRuntimeException {
checkConn(conn); checkConn(conn);
if (null == page) { if (null == page) {
return SqlExecutor.query(conn, sqlBuilder, rsh); return SqlExecutor.query(conn, sqlBuilder, rsh);
} }
return SqlExecutor.queryAndClosePs(dialect.psForPage(conn, sqlBuilder, page), rsh); final PreparedStatement ps;
try {
ps = dialect.psForPage(conn, sqlBuilder, page);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
return SqlExecutor.queryAndClosePs(ps, rsh);
} }
//---------------------------------------------------------------------------- CRUD end //---------------------------------------------------------------------------- CRUD end

View File

@ -5,7 +5,6 @@ import cn.hutool.core.text.StrUtil;
import cn.hutool.db.dialect.Dialect; import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory; import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.ds.DSFactory; import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.sql.Wrapper;
import cn.hutool.log.Log; import cn.hutool.log.Log;
import cn.hutool.log.LogFactory; import cn.hutool.log.LogFactory;
@ -24,7 +23,7 @@ import java.sql.Savepoint;
* @author loolly * @author loolly
* *
*/ */
public class Session extends AbstractDb implements Closeable { public class Session extends AbstractDb<Session> implements Closeable {
private static final long serialVersionUID = 3421251905539056945L; private static final long serialVersionUID = 3421251905539056945L;
private final static Log log = LogFactory.get(); private final static Log log = LogFactory.get();
@ -34,7 +33,7 @@ public class Session extends AbstractDb implements Closeable {
* @return Session * @return Session
* @since 3.2.3 * @since 3.2.3
*/ */
public static Session create() { public static Session of() {
return new Session(DSFactory.get()); return new Session(DSFactory.get());
} }
@ -45,7 +44,7 @@ public class Session extends AbstractDb implements Closeable {
* @return Session * @return Session
* @since 4.0.11 * @since 4.0.11
*/ */
public static Session create(final String group) { public static Session of(final String group) {
return new Session(DSFactory.get(group)); return new Session(DSFactory.get(group));
} }
@ -55,7 +54,7 @@ public class Session extends AbstractDb implements Closeable {
* @param ds 数据源 * @param ds 数据源
* @return Session * @return Session
*/ */
public static Session create(final DataSource ds) { public static Session of(final DataSource ds) {
return new Session(ds); return new Session(ds);
} }
@ -90,38 +89,32 @@ public class Session extends AbstractDb implements Closeable {
} }
// ---------------------------------------------------------------------------- Constructor end // ---------------------------------------------------------------------------- Constructor end
// ---------------------------------------------------------------------------- Getters and Setters end
/**
* 获得{@link SqlConnRunner}
*
* @return {@link SqlConnRunner}
*/
@Override
public SqlConnRunner getRunner() {
return runner;
}
// ---------------------------------------------------------------------------- Getters and Setters end
// ---------------------------------------------------------------------------- Transaction method start // ---------------------------------------------------------------------------- Transaction method start
/** /**
* 开始事务 * 开始事务
* *
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public void beginTransaction() throws SQLException { public void beginTransaction() throws DbRuntimeException {
final Connection conn = getConnection(); final Connection conn = getConnection();
checkTransactionSupported(conn); checkTransactionSupported(conn);
try {
conn.setAutoCommit(false); conn.setAutoCommit(false);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
* 提交事务 * 提交事务
* *
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public void commit() throws SQLException { public void commit() throws DbRuntimeException {
try { try {
getConnection().commit(); getConnection().commit();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
try { try {
getConnection().setAutoCommit(true); // 事务结束恢复自动提交 getConnection().setAutoCommit(true); // 事务结束恢复自动提交
@ -134,11 +127,13 @@ public class Session extends AbstractDb implements Closeable {
/** /**
* 回滚事务 * 回滚事务
* *
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public void rollback() throws SQLException { public void rollback() throws DbRuntimeException {
try { try {
getConnection().rollback(); getConnection().rollback();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
try { try {
getConnection().setAutoCommit(true); // 事务结束恢复自动提交 getConnection().setAutoCommit(true); // 事务结束恢复自动提交
@ -170,11 +165,13 @@ public class Session extends AbstractDb implements Closeable {
* 回滚到某个保存点保存点的设置请使用setSavepoint方法 * 回滚到某个保存点保存点的设置请使用setSavepoint方法
* *
* @param savepoint 保存点 * @param savepoint 保存点
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public void rollback(final Savepoint savepoint) throws SQLException { public void rollback(final Savepoint savepoint) throws DbRuntimeException {
try { try {
getConnection().rollback(savepoint); getConnection().rollback(savepoint);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
try { try {
getConnection().setAutoCommit(true); // 事务结束恢复自动提交 getConnection().setAutoCommit(true); // 事务结束恢复自动提交
@ -207,10 +204,14 @@ public class Session extends AbstractDb implements Closeable {
* 设置保存点 * 设置保存点
* *
* @return 保存点对象 * @return 保存点对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public Savepoint setSavepoint() throws SQLException { public Savepoint setSavepoint() throws DbRuntimeException {
try {
return getConnection().setSavepoint(); return getConnection().setSavepoint();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -234,55 +235,46 @@ public class Session extends AbstractDb implements Closeable {
* Connection.TRANSACTION_SERIALIZABLE 禁止脏读不可重复读和幻读<br> * Connection.TRANSACTION_SERIALIZABLE 禁止脏读不可重复读和幻读<br>
* *
* @param level 隔离级别 * @param level 隔离级别
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public void setTransactionIsolation(final int level) throws SQLException { public void setTransactionIsolation(final int level) throws DbRuntimeException {
try {
if (getConnection().getMetaData().supportsTransactionIsolationLevel(level) == false) { if (getConnection().getMetaData().supportsTransactionIsolationLevel(level) == false) {
throw new SQLException(StrUtil.format("Transaction isolation [{}] not support!", level)); throw new DbRuntimeException(StrUtil.format("Transaction isolation [{}] not support!", level));
} }
getConnection().setTransactionIsolation(level); getConnection().setTransactionIsolation(level);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
* 在事务中执行操作通过实现{@link VoidFunc1}接口的call方法执行多条SQL语句从而完成事务 * 在事务中执行操作通过实现{@link VoidFunc1}接口的call方法执行多条SQL语句从而完成事务
* *
* @param func 函数抽象在函数中执行多个SQL操作多个操作会被合并为同一事务 * @param func 函数抽象在函数中执行多个SQL操作多个操作会被合并为同一事务
* @throws SQLException SQL异常 * @throws DbRuntimeException SQL异常
* @since 3.2.3 * @since 3.2.3
*/ */
public void tx(final VoidFunc1<Session> func) throws SQLException { public void tx(final VoidFunc1<Session> func) throws DbRuntimeException {
try { try {
beginTransaction(); beginTransaction();
func.call(this); func.call(this);
commit(); commit();
} catch (final Throwable e) { } catch (final Throwable e) {
quietRollback(); quietRollback();
throw (e instanceof SQLException) ? (SQLException) e : new SQLException(e); throw new DbRuntimeException(e);
} }
} }
// ---------------------------------------------------------------------------- Transaction method end // ---------------------------------------------------------------------------- Transaction method end
// ---------------------------------------------------------------------------- Getters and Setters start
@Override @Override
public Session setWrapper(final Character wrapperChar) { public Connection getConnection() throws DbRuntimeException {
return (Session) super.setWrapper(wrapperChar); try {
}
@Override
public Session setWrapper(final Wrapper wrapper) {
return (Session) super.setWrapper(wrapper);
}
@Override
public Session disableWrapper() {
return (Session) super.disableWrapper();
}
// ---------------------------------------------------------------------------- Getters and Setters end
@Override
public Connection getConnection() throws SQLException {
return ThreadLocalConnection.INSTANCE.get(this.ds); return ThreadLocalConnection.INSTANCE.get(this.ds);
} catch (final SQLException e) {
throw new RuntimeException(e);
}
} }
@Override @Override

View File

@ -1,376 +0,0 @@
package cn.hutool.db;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.dialect.Dialect;
import cn.hutool.db.dialect.DialectFactory;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.handler.HandleHelper;
import cn.hutool.db.handler.PageResultHandler;
import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.Condition.LikeType;
import cn.hutool.db.sql.Query;
import cn.hutool.db.sql.SqlBuilder;
import cn.hutool.db.sql.SqlUtil;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
/**
* SQL执行类<br>
* 此执行类只接受方言参数不需要数据源只有在执行方法时需要数据库连接对象<br>
* 此对象存在的意义在于可以由使用者自定义数据库连接对象并执行多个方法方便事务的统一控制或减少连接对象的创建关闭<br>
* 相比{@link DialectRunner}此类中提供了更多重载方法
*
* @author Luxiaolei
*/
public class SqlConnRunner extends DialectRunner {
private static final long serialVersionUID = 1L;
/**
* 实例化一个新的SQL运行对象
*
* @param dialect 方言
* @return SQL执行类
*/
public static SqlConnRunner create(final Dialect dialect) {
return new SqlConnRunner(dialect);
}
/**
* 实例化一个新的SQL运行对象
*
* @param ds 数据源
* @return SQL执行类
*/
public static SqlConnRunner create(final DataSource ds) {
return new SqlConnRunner(DialectFactory.getDialect(ds));
}
/**
* 实例化一个新的SQL运行对象
*
* @param driverClassName 驱动类名
* @return SQL执行类
*/
public static SqlConnRunner create(final String driverClassName) {
return new SqlConnRunner(driverClassName);
}
//------------------------------------------------------- Constructor start
/**
* 构造
*
* @param dialect 方言
*/
public SqlConnRunner(final Dialect dialect) {
super(dialect);
}
/**
* 构造
*
* @param driverClassName 驱动类名用于识别方言
*/
public SqlConnRunner(final String driverClassName) {
super(driverClassName);
}
//------------------------------------------------------- Constructor end
//---------------------------------------------------------------------------- CRUD start
/**
* 批量插入数据<br>
* 需要注意的是批量插入每一条数据结构必须一致批量插入数据时会获取第一条数据的字段结构之后的数据会按照这个格式插入<br>
* 也就是说假如第一条数据只有2个字段后边数据多于这两个字段的部分将被抛弃
* 此方法不会关闭Connection
*
* @param conn 数据库连接
* @param records 记录列表记录KV必须严格一致
* @return 插入行数
* @throws SQLException SQL执行异常
*/
public int[] insert(final Connection conn, final Collection<Entity> records) throws SQLException {
return insert(conn, records.toArray(new Entity[0]));
}
/**
* 插入数据<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接
* @param record 记录
* @return 插入行数
* @throws SQLException SQL执行异常
*/
public int insert(final Connection conn, final Entity record) throws SQLException {
return insert(conn, new Entity[]{record})[0];
}
/**
* 插入数据<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接
* @param record 记录
* @return 主键列表
* @throws SQLException SQL执行异常
*/
public List<Object> insertForGeneratedKeys(final Connection conn, final Entity record) throws SQLException {
return insert(conn, record, HandleHelper::handleRowToList);
}
/**
* 插入数据<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接
* @param record 记录
* @return 自增主键
* @throws SQLException SQL执行异常
*/
public Long insertForGeneratedKey(final Connection conn, final Entity record) throws SQLException {
return insert(conn, record, (rs) -> {
Long generatedKey = null;
if (rs != null && rs.next()) {
try {
generatedKey = rs.getLong(1);
} catch (final SQLException e) {
// 自增主键不为数字或者为Oracle的rowid跳过
}
}
return generatedKey;
});
}
/**
* 查询<br>
* 此方法不会关闭Connection
*
* @param <T> 结果对象类型
* @param conn 数据库连接对象
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param rsh 结果集处理对象
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public <T> T find(final Connection conn, final Collection<String> fields, final Entity where, final RsHandler<T> rsh) throws SQLException {
return find(conn, Query.of(where).setFields(fields), rsh);
}
/**
* 查询返回指定字段列表<br>
* 此方法不会关闭Connection
*
* @param <T> 结果对象类型
* @param conn 数据库连接对象
* @param where 条件实体类包含表名
* @param rsh 结果集处理对象
* @param fields 字段列表可变长参数如果无值表示查询全部字段
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public <T> T find(final Connection conn, final Entity where, final RsHandler<T> rsh, final String... fields) throws SQLException {
return find(conn, CollUtil.newArrayList(fields), where, rsh);
}
/**
* 查询数据列表返回字段在where参数中定义
*
* @param conn 数据库连接对象
* @param where 条件实体类包含表名
* @return 数据对象列表
* @throws SQLException SQL执行异常
* @since 3.2.1
*/
public List<Entity> find(final Connection conn, final Entity where) throws SQLException {
return find(conn, where.getFieldNames(), where, new EntityListHandler(this.caseInsensitive));
}
/**
* 查询数据列表返回所有字段
*
* @param conn 数据库连接对象
* @param where 条件实体类包含表名
* @return 数据对象列表
* @throws SQLException SQL执行异常
*/
public List<Entity> findAll(final Connection conn, final Entity where) throws SQLException {
return find(conn, where, new EntityListHandler(this.caseInsensitive));
}
/**
* 查询数据列表返回所有字段
*
* @param conn 数据库连接对象
* @param tableName 表名
* @return 数据对象列表
* @throws SQLException SQL执行异常
*/
public List<Entity> findAll(final Connection conn, final String tableName) throws SQLException {
return findAll(conn, Entity.create(tableName));
}
/**
* 根据某个字段名条件查询数据列表返回所有字段
*
* @param conn 数据库连接对象
* @param tableName 表名
* @param field 字段名
* @param value 字段值
* @return 数据对象列表
* @throws SQLException SQL执行异常
*/
public List<Entity> findBy(final Connection conn, final String tableName, final String field, final Object value) throws SQLException {
return findAll(conn, Entity.create(tableName).set(field, value));
}
/**
* 根据某个字段名条件查询数据列表返回所有字段
*
* @param conn 数据库连接对象
* @param tableName 表名
* @param field 字段名
* @param value 字段值
* @param likeType {@link LikeType}
* @return 数据对象列表
* @throws SQLException SQL执行异常
*/
public List<Entity> findLike(final Connection conn, final String tableName, final String field, final String value, final LikeType likeType) throws SQLException {
return findAll(conn, Entity.create(tableName).set(field, SqlUtil.buildLikeValue(value, likeType, true)));
}
/**
* 根据某个字段名条件查询数据列表返回所有字段
*
* @param conn 数据库连接对象
* @param tableName 表名
* @param field 字段名
* @param values 字段值列表
* @return 数据对象列表
* @throws SQLException SQL执行异常
*/
public List<Entity> findIn(final Connection conn, final String tableName, final String field, final Object... values) throws SQLException {
return findAll(conn, Entity.create(tableName).set(field, values));
}
/**
* 获取查询结果总数生成类似于 SELECT count(1) from (sql) as _count
*
* @param conn 数据库连接对象
* @param selectSql 查询语句
* @param params 查询参数
* @return 结果数
* @throws SQLException SQL异常
* @since 5.6.6
*/
public long count(final Connection conn, final CharSequence selectSql, final Object... params) throws SQLException {
return count(conn, SqlBuilder.of(selectSql).addParams(params));
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param <T> 结果对象类型
* @param conn 数据库连接对象
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param pageNumber 页码
* @param numPerPage 每页条目数
* @param rsh 结果集处理对象
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public <T> T page(final Connection conn, final Collection<String> fields, final Entity where, final int pageNumber, final int numPerPage, final RsHandler<T> rsh) throws SQLException {
return page(conn, Query.of(where).setFields(fields).setPage(new Page(pageNumber, numPerPage)), rsh);
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param sqlBuilder SQL构建器可以使用{@link SqlBuilder#of(CharSequence)} 包装普通SQL
* @param page 分页对象
* @return 结果对象
* @throws SQLException SQL执行异常
* @since 5.5.3
*/
public PageResult<Entity> page(final Connection conn, final SqlBuilder sqlBuilder, final Page page) throws SQLException {
final PageResultHandler pageResultHandler = new PageResultHandler(
new PageResult<>(page.getPageNumber(), page.getPageSize(), (int) count(conn, sqlBuilder)),
this.caseInsensitive);
return page(conn, sqlBuilder, page, pageResultHandler);
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param page 页码
* @param numPerPage 每页条目数
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public PageResult<Entity> page(final Connection conn, final Collection<String> fields, final Entity where, final int page, final int numPerPage) throws SQLException {
return page(conn, fields, where, new Page(page, numPerPage));
}
/**
* 分页全字段查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param where 条件实体类包含表名
* @param page 分页对象
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public PageResult<Entity> page(final Connection conn, final Entity where, final Page page) throws SQLException {
return this.page(conn, null, where, page);
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param conn 数据库连接对象
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param page 分页对象
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public PageResult<Entity> page(final Connection conn, final Collection<String> fields, final Entity where, final Page page) throws SQLException {
final PageResultHandler pageResultHandler = new PageResultHandler(
new PageResult<>(page.getPageNumber(), page.getPageSize(), (int) count(conn, where)),
this.caseInsensitive);
return page(conn, fields, where, page, pageResultHandler);
}
/**
* 分页查询<br>
* 此方法不会关闭Connection
*
* @param <T> 结果类型取决于 {@link RsHandler} 的处理逻辑
* @param conn 数据库连接对象
* @param fields 返回的字段列表null则返回所有字段
* @param where 条件实体类包含表名
* @param page 分页对象
* @param handler 结果集处理器
* @return 结果对象
* @throws SQLException SQL执行异常
*/
public <T> T page(final Connection conn, final Collection<String> fields, final Entity where, final Page page, final RsHandler<T> handler) throws SQLException {
return this.page(conn, Query.of(where).setFields(fields).setPage(page), handler);
}
//---------------------------------------------------------------------------- CRUD end
}

View File

@ -6,7 +6,7 @@ import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.db.handler.HandleHelper; import cn.hutool.db.handler.ResultSetUtil;
import cn.hutool.db.handler.RsHandler; import cn.hutool.db.handler.RsHandler;
import cn.hutool.db.sql.NamedSql; import cn.hutool.db.sql.NamedSql;
import cn.hutool.db.sql.SqlBuilder; import cn.hutool.db.sql.SqlBuilder;
@ -259,7 +259,7 @@ public class StatementUtil {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
*/ */
public static List<Object> getGeneratedKeys(final Statement ps) throws SQLException { public static List<Object> getGeneratedKeys(final Statement ps) throws SQLException {
return getGeneratedKeys(ps, HandleHelper::handleRowToList); return getGeneratedKeys(ps, ResultSetUtil::handleRowToList);
} }
/** /**

View File

@ -35,6 +35,6 @@ public class BeanHandler<E> implements RsHandler<E>{
public E handle(final ResultSet rs) throws SQLException { public E handle(final ResultSet rs) throws SQLException {
final ResultSetMetaData meta = rs.getMetaData(); final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount(); final int columnCount = meta.getColumnCount();
return rs.next() ? HandleHelper.handleRow(columnCount, meta, rs, this.elementBeanType) : null; return rs.next() ? ResultSetUtil.toBean(columnCount, meta, rs, this.elementBeanType) : null;
} }
} }

View File

@ -38,6 +38,6 @@ public class BeanListHandler<E> implements RsHandler<List<E>> {
@Override @Override
public List<E> handle(final ResultSet rs) throws SQLException { public List<E> handle(final ResultSet rs) throws SQLException {
return HandleHelper.handleRsToBeanList(rs, new ArrayList<>(), elementBeanType); return ResultSetUtil.toBeanList(rs, new ArrayList<>(), elementBeanType);
} }
} }

View File

@ -47,6 +47,6 @@ public class EntityHandler implements RsHandler<Entity>{
final ResultSetMetaData meta = rs.getMetaData(); final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount(); final int columnCount = meta.getColumnCount();
return rs.next() ? HandleHelper.handleRow(columnCount, meta, rs, this.caseInsensitive) : null; return rs.next() ? ResultSetUtil.toBean(columnCount, meta, rs, this.caseInsensitive) : null;
} }
} }

View File

@ -44,6 +44,6 @@ public class EntityListHandler implements RsHandler<List<Entity>>{
@Override @Override
public List<Entity> handle(final ResultSet rs) throws SQLException { public List<Entity> handle(final ResultSet rs) throws SQLException {
return HandleHelper.handleRs(rs, new ArrayList<>(), this.caseInsensitive); return ResultSetUtil.toEntityList(rs, new ArrayList<>(), this.caseInsensitive);
} }
} }

View File

@ -43,6 +43,6 @@ public class EntitySetHandler implements RsHandler<LinkedHashSet<Entity>>{
@Override @Override
public LinkedHashSet<Entity> handle(final ResultSet rs) throws SQLException { public LinkedHashSet<Entity> handle(final ResultSet rs) throws SQLException {
return HandleHelper.handleRs(rs, new LinkedHashSet<>(), this.caseInsensitive); return ResultSetUtil.toEntityList(rs, new LinkedHashSet<>(), this.caseInsensitive);
} }
} }

View File

@ -55,6 +55,6 @@ public class PageResultHandler implements RsHandler<PageResult<Entity>> {
@Override @Override
public PageResult<Entity> handle(final ResultSet rs) throws SQLException { public PageResult<Entity> handle(final ResultSet rs) throws SQLException {
return HandleHelper.handleRs(rs, pageResult, this.caseInsensitive); return ResultSetUtil.toEntityList(rs, pageResult, this.caseInsensitive);
} }
} }

View File

@ -8,6 +8,7 @@ import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.reflect.ReflectUtil; import cn.hutool.core.reflect.ReflectUtil;
import cn.hutool.core.text.StrUtil; import cn.hutool.core.text.StrUtil;
import cn.hutool.core.reflect.TypeUtil; import cn.hutool.core.reflect.TypeUtil;
import cn.hutool.db.DbRuntimeException;
import cn.hutool.db.Entity; import cn.hutool.db.Entity;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -24,10 +25,9 @@ import java.util.Map;
/** /**
* 数据结果集处理辅助类 * 数据结果集处理辅助类
* *
* @author loolly * @author looly
*
*/ */
public class HandleHelper { public class ResultSetUtil {
/** /**
* 处理单条数据 * 处理单条数据
@ -41,8 +41,8 @@ public class HandleHelper {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
* @since 3.3.1 * @since 3.3.1
*/ */
public static <T> T handleRow(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final T bean) throws SQLException { public static <T> T toBean(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final T bean) throws SQLException {
return handleRow(columnCount, meta, rs).toBeanIgnoreCase(bean); return toEntity(columnCount, meta, rs).toBeanIgnoreCase(bean);
} }
/** /**
@ -58,27 +58,27 @@ public class HandleHelper {
* @since 3.3.1 * @since 3.3.1
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public static <T> T handleRow(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final Class<T> beanClass) throws SQLException { public static <T> T toBean(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final Class<T> beanClass) throws SQLException {
Assert.notNull(beanClass, "Bean Class must be not null !"); Assert.notNull(beanClass, "Bean Class must be not null !");
if(beanClass.isArray()) { if (beanClass.isArray()) {
//返回数组 //返回数组
final Class<?> componentType = beanClass.getComponentType(); final Class<?> componentType = beanClass.getComponentType();
final Object[] result = ArrayUtil.newArray(componentType, columnCount); final Object[] result = ArrayUtil.newArray(componentType, columnCount);
for(int i = 0,j = 1; i < columnCount; i++, j++) { for (int i = 0, j = 1; i < columnCount; i++, j++) {
result[i] = getColumnValue(rs, j, meta.getColumnType(j), componentType); result[i] = getColumnValue(rs, j, meta.getColumnType(j), componentType);
} }
return (T) result; return (T) result;
} else if(Iterable.class.isAssignableFrom(beanClass)) { } else if (Iterable.class.isAssignableFrom(beanClass)) {
//集合 //集合
final Object[] objRow = handleRow(columnCount, meta, rs, Object[].class); final Object[] objRow = toBean(columnCount, meta, rs, Object[].class);
return Convert.convert(beanClass, objRow); return Convert.convert(beanClass, objRow);
} else if(beanClass.isAssignableFrom(Entity.class)) { } else if (beanClass.isAssignableFrom(Entity.class)) {
//Entity的父类都可按照Entity返回 //Entity的父类都可按照Entity返回
return (T) handleRow(columnCount, meta, rs); return (T) toEntity(columnCount, meta, rs);
} else if(String.class == beanClass) { } else if (String.class == beanClass) {
//字符串 //字符串
final Object[] objRow = handleRow(columnCount, meta, rs, Object[].class); final Object[] objRow = toBean(columnCount, meta, rs, Object[].class);
return (T) StrUtil.join(", ", objRow); return (T) StrUtil.join(", ", objRow);
} }
@ -93,12 +93,12 @@ public class HandleHelper {
for (int i = 1; i <= columnCount; i++) { for (int i = 1; i <= columnCount; i++) {
columnLabel = meta.getColumnLabel(i); columnLabel = meta.getColumnLabel(i);
pd = propMap.get(columnLabel); pd = propMap.get(columnLabel);
if(null == pd) { if (null == pd) {
// 尝试驼峰命名风格 // 尝试驼峰命名风格
pd = propMap.get(StrUtil.toCamelCase(columnLabel)); pd = propMap.get(StrUtil.toCamelCase(columnLabel));
} }
setter = (null == pd) ? null : pd.getSetter(); setter = (null == pd) ? null : pd.getSetter();
if(null != setter) { if (null != setter) {
value = getColumnValue(rs, i, meta.getColumnType(i), TypeUtil.getFirstParamType(setter)); value = getColumnValue(rs, i, meta.getColumnType(i), TypeUtil.getFirstParamType(setter));
ReflectUtil.invokeWithCheck(bean, setter, value); ReflectUtil.invokeWithCheck(bean, setter, value);
} }
@ -115,8 +115,8 @@ public class HandleHelper {
* @return 每一行的Entity * @return 每一行的Entity
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
*/ */
public static Entity handleRow(final int columnCount, final ResultSetMetaData meta, final ResultSet rs) throws SQLException { public static Entity toEntity(final int columnCount, final ResultSetMetaData meta, final ResultSet rs) throws SQLException {
return handleRow(columnCount, meta, rs, false); return toBean(columnCount, meta, rs, false);
} }
/** /**
@ -130,8 +130,8 @@ public class HandleHelper {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
* @since 4.5.16 * @since 4.5.16
*/ */
public static Entity handleRow(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final boolean caseInsensitive) throws SQLException { public static Entity toBean(final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final boolean caseInsensitive) throws SQLException {
return handleRow(new Entity(null, caseInsensitive), columnCount, meta, rs, true); return toBean(new Entity(null, caseInsensitive), columnCount, meta, rs, true);
} }
/** /**
@ -147,7 +147,7 @@ public class HandleHelper {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
* @since 3.3.1 * @since 3.3.1
*/ */
public static <T extends Entity> T handleRow(final T row, final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final boolean withMetaInfo) throws SQLException { public static <T extends Entity> T toBean(final T row, final int columnCount, final ResultSetMetaData meta, final ResultSet rs, final boolean withMetaInfo) throws SQLException {
int type; int type;
for (int i = 1; i <= columnCount; i++) { for (int i = 1; i <= columnCount; i++) {
type = meta.getColumnType(i); type = meta.getColumnType(i);
@ -156,7 +156,7 @@ public class HandleHelper {
if (withMetaInfo) { if (withMetaInfo) {
try { try {
row.setTableName(meta.getTableName(1)); row.setTableName(meta.getTableName(1));
} catch (final SQLException ignore){ } catch (final SQLException ignore) {
//issue#I2AGLU@Gitee //issue#I2AGLU@Gitee
// Hive等NoSQL中无表的概念此处报错跳过 // Hive等NoSQL中无表的概念此处报错跳过
} }
@ -172,10 +172,10 @@ public class HandleHelper {
* @return 每一行的Entity * @return 每一行的Entity
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
*/ */
public static Entity handleRow(final ResultSet rs) throws SQLException { public static Entity toEntity(final ResultSet rs) throws SQLException {
final ResultSetMetaData meta = rs.getMetaData(); final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount(); final int columnCount = meta.getColumnCount();
return handleRow(columnCount, meta, rs); return toEntity(columnCount, meta, rs);
} }
/** /**
@ -206,8 +206,8 @@ public class HandleHelper {
* @return Entity列表 * @return Entity列表
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
*/ */
public static <T extends Collection<Entity>> T handleRs(final ResultSet rs, final T collection) throws SQLException { public static <T extends Collection<Entity>> T toEntityList(final ResultSet rs, final T collection) throws SQLException {
return handleRs(rs, collection, false); return toEntityList(rs, collection, false);
} }
/** /**
@ -221,12 +221,12 @@ public class HandleHelper {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
* @since 4.5.16 * @since 4.5.16
*/ */
public static <T extends Collection<Entity>> T handleRs(final ResultSet rs, final T collection, final boolean caseInsensitive) throws SQLException { public static <T extends Collection<Entity>> T toEntityList(final ResultSet rs, final T collection, final boolean caseInsensitive) throws SQLException {
final ResultSetMetaData meta = rs.getMetaData(); final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount(); final int columnCount = meta.getColumnCount();
while (rs.next()) { while (rs.next()) {
collection.add(HandleHelper.handleRow(columnCount, meta, rs, caseInsensitive)); collection.add(ResultSetUtil.toBean(columnCount, meta, rs, caseInsensitive));
} }
return collection; return collection;
@ -244,18 +244,39 @@ public class HandleHelper {
* @throws SQLException SQL执行异常 * @throws SQLException SQL执行异常
* @since 3.1.0 * @since 3.1.0
*/ */
public static <E, T extends Collection<E>> T handleRsToBeanList(final ResultSet rs, final T collection, final Class<E> elementBeanType) throws SQLException { public static <E, T extends Collection<E>> T toBeanList(final ResultSet rs, final T collection, final Class<E> elementBeanType) throws SQLException {
final ResultSetMetaData meta = rs.getMetaData(); final ResultSetMetaData meta = rs.getMetaData();
final int columnCount = meta.getColumnCount(); final int columnCount = meta.getColumnCount();
while (rs.next()) { while (rs.next()) {
collection.add(handleRow(columnCount, meta, rs, elementBeanType)); collection.add(toBean(columnCount, meta, rs, elementBeanType));
} }
return collection; return collection;
} }
/**
* 结果集读取为一个Long值一版用于插入时返回主键等<br>
* 当有多个值返回时只取第一个
*
* @param rs 数据集
* @return long值
* @throws SQLException SQL执行异常
*/
public static Long toLong(final ResultSet rs) throws SQLException {
Long generatedKey = null;
if (rs != null && rs.next()) {
try {
generatedKey = rs.getLong(1);
} catch (final DbRuntimeException e) {
// 自增主键不为数字或者为Oracle的rowid跳过
}
}
return generatedKey;
}
// -------------------------------------------------------------------------------------------------------------- Private method start // -------------------------------------------------------------------------------------------------------------- Private method start
/** /**
* 获取字段值<br> * 获取字段值<br>
* 针对日期时间等做单独处理判断 * 针对日期时间等做单独处理判断
@ -271,9 +292,9 @@ public class HandleHelper {
Object rawValue = null; Object rawValue = null;
switch (type) { switch (type) {
case Types.TIMESTAMP: case Types.TIMESTAMP:
try{ try {
rawValue = rs.getTimestamp(columnIndex); rawValue = rs.getTimestamp(columnIndex);
} catch (final SQLException ignore){ } catch (final SQLException ignore) {
// issue#776@Github // issue#776@Github
// 当数据库中日期为0000-00-00 00:00:00报错转为null // 当数据库中日期为0000-00-00 00:00:00报错转为null
} }

View File

@ -25,7 +25,7 @@ public class ValueListHandler implements RsHandler<List<List<Object>>>{
public List<List<Object>> handle(final ResultSet rs) throws SQLException { public List<List<Object>> handle(final ResultSet rs) throws SQLException {
final ArrayList<List<Object>> result = new ArrayList<>(); final ArrayList<List<Object>> result = new ArrayList<>();
while (rs.next()) { while (rs.next()) {
result.add(HandleHelper.handleRowToList(rs)); result.add(ResultSetUtil.handleRowToList(rs));
} }
return result; return result;
} }

View File

@ -2,6 +2,7 @@ package cn.hutool.db.sql;
import cn.hutool.core.collection.iter.ArrayIter; import cn.hutool.core.collection.iter.ArrayIter;
import cn.hutool.core.lang.func.Func1; import cn.hutool.core.lang.func.Func1;
import cn.hutool.db.DbRuntimeException;
import cn.hutool.db.DbUtil; import cn.hutool.db.DbUtil;
import cn.hutool.db.StatementUtil; import cn.hutool.db.StatementUtil;
import cn.hutool.db.handler.RsHandler; import cn.hutool.db.handler.RsHandler;
@ -19,7 +20,6 @@ import java.util.Map;
* 此方法为JDBC的简单封装与数据库类型无关 * 此方法为JDBC的简单封装与数据库类型无关
* *
* @author loolly * @author loolly
*
*/ */
public class SqlExecutor { public class SqlExecutor {
@ -32,10 +32,10 @@ public class SqlExecutor {
* @param sql SQL使用name做为占位符例如:name * @param sql SQL使用name做为占位符例如:name
* @param paramMap 参数Map * @param paramMap 参数Map
* @return 影响的行数 * @return 影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.10 * @since 4.0.10
*/ */
public static int execute(final Connection conn, final String sql, final Map<String, Object> paramMap) throws SQLException { public static int execute(final Connection conn, final String sql, final Map<String, Object> paramMap) throws DbRuntimeException {
final NamedSql namedSql = new NamedSql(sql, paramMap); final NamedSql namedSql = new NamedSql(sql, paramMap);
return execute(conn, namedSql.getSql(), namedSql.getParams()); return execute(conn, namedSql.getSql(), namedSql.getParams());
} }
@ -49,13 +49,15 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return 影响的行数 * @return 影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static int execute(final Connection conn, final String sql, final Object... params) throws SQLException { public static int execute(final Connection conn, final String sql, final Object... params) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = StatementUtil.prepareStatement(conn, sql, params); ps = StatementUtil.prepareStatement(conn, sql, params);
return ps.executeUpdate(); return ps.executeUpdate();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -69,13 +71,15 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return 如果执行后第一个结果是ResultSet则返回true否则返回false * @return 如果执行后第一个结果是ResultSet则返回true否则返回false
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static boolean call(final Connection conn, final String sql, final Object... params) throws SQLException { public static boolean call(final Connection conn, final String sql, final Object... params) throws DbRuntimeException {
CallableStatement call = null; CallableStatement call = null;
try { try {
call = StatementUtil.prepareCall(conn, sql, params); call = StatementUtil.prepareCall(conn, sql, params);
return call.execute(); return call.execute();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(call); DbUtil.close(call);
} }
@ -89,11 +93,15 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return ResultSet * @return ResultSet
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.1.4 * @since 4.1.4
*/ */
public static ResultSet callQuery(final Connection conn, final String sql, final Object... params) throws SQLException { public static ResultSet callQuery(final Connection conn, final String sql, final Object... params) throws DbRuntimeException {
try {
return StatementUtil.prepareCall(conn, sql, params).executeQuery(); return StatementUtil.prepareCall(conn, sql, params).executeQuery();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -105,10 +113,10 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param paramMap 参数Map * @param paramMap 参数Map
* @return 主键 * @return 主键
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.10 * @since 4.0.10
*/ */
public static Long executeForGeneratedKey(final Connection conn, final String sql, final Map<String, Object> paramMap) throws SQLException { public static Long executeForGeneratedKey(final Connection conn, final String sql, final Map<String, Object> paramMap) throws DbRuntimeException {
final NamedSql namedSql = new NamedSql(sql, paramMap); final NamedSql namedSql = new NamedSql(sql, paramMap);
return executeForGeneratedKey(conn, namedSql.getSql(), namedSql.getParams()); return executeForGeneratedKey(conn, namedSql.getSql(), namedSql.getParams());
} }
@ -122,9 +130,9 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param params 参数 * @param params 参数
* @return 主键 * @return 主键
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static Long executeForGeneratedKey(final Connection conn, final String sql, final Object... params) throws SQLException { public static Long executeForGeneratedKey(final Connection conn, final String sql, final Object... params) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
ResultSet rs = null; ResultSet rs = null;
try { try {
@ -139,6 +147,8 @@ public class SqlExecutor {
} }
} }
return null; return null;
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
DbUtil.close(rs); DbUtil.close(rs);
@ -154,13 +164,15 @@ public class SqlExecutor {
* @param sql SQL * @param sql SQL
* @param paramsBatch 批量的参数 * @param paramsBatch 批量的参数
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static int[] executeBatch(final Connection conn, final String sql, final Iterable<Object[]> paramsBatch) throws SQLException { public static int[] executeBatch(final Connection conn, final String sql, final Iterable<Object[]> paramsBatch) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = StatementUtil.prepareStatementForBatch(conn, sql, paramsBatch); ps = StatementUtil.prepareStatementForBatch(conn, sql, paramsBatch);
return ps.executeBatch(); return ps.executeBatch();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -174,10 +186,10 @@ public class SqlExecutor {
* @param conn 数据库连接对象 * @param conn 数据库连接对象
* @param sqls SQL列表 * @param sqls SQL列表
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.5.6 * @since 4.5.6
*/ */
public static int[] executeBatch(final Connection conn, final String... sqls) throws SQLException { public static int[] executeBatch(final Connection conn, final String... sqls) throws DbRuntimeException {
return executeBatch(conn, new ArrayIter<>(sqls)); return executeBatch(conn, new ArrayIter<>(sqls));
} }
@ -189,10 +201,10 @@ public class SqlExecutor {
* @param conn 数据库连接对象 * @param conn 数据库连接对象
* @param sqls SQL列表 * @param sqls SQL列表
* @return 每个SQL执行影响的行数 * @return 每个SQL执行影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.5.6 * @since 4.5.6
*/ */
public static int[] executeBatch(final Connection conn, final Iterable<String> sqls) throws SQLException { public static int[] executeBatch(final Connection conn, final Iterable<String> sqls) throws DbRuntimeException {
Statement statement = null; Statement statement = null;
try { try {
statement = conn.createStatement(); statement = conn.createStatement();
@ -200,6 +212,8 @@ public class SqlExecutor {
statement.addBatch(sql); statement.addBatch(sql);
} }
return statement.executeBatch(); return statement.executeBatch();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(statement); DbUtil.close(statement);
} }
@ -215,10 +229,10 @@ public class SqlExecutor {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param paramMap 参数对 * @param paramMap 参数对
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.0.10 * @since 4.0.10
*/ */
public static <T> T query(final Connection conn, final String sql, final RsHandler<T> rsh, final Map<String, Object> paramMap) throws SQLException { public static <T> T query(final Connection conn, final String sql, final RsHandler<T> rsh, final Map<String, Object> paramMap) throws DbRuntimeException {
final NamedSql namedSql = new NamedSql(sql, paramMap); final NamedSql namedSql = new NamedSql(sql, paramMap);
return query(conn, namedSql.getSql(), rsh, namedSql.getParams()); return query(conn, namedSql.getSql(), rsh, namedSql.getParams());
} }
@ -232,10 +246,10 @@ public class SqlExecutor {
* @param sqlBuilder SQL构建器包含参数 * @param sqlBuilder SQL构建器包含参数
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.5.3 * @since 5.5.3
*/ */
public static <T> T query(final Connection conn, final SqlBuilder sqlBuilder, final RsHandler<T> rsh) throws SQLException { public static <T> T query(final Connection conn, final SqlBuilder sqlBuilder, final RsHandler<T> rsh) throws DbRuntimeException {
return query(conn, sqlBuilder.build(), rsh, sqlBuilder.getParamValueArray()); return query(conn, sqlBuilder.build(), rsh, sqlBuilder.getParamValueArray());
} }
@ -249,13 +263,15 @@ public class SqlExecutor {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static <T> T query(final Connection conn, final String sql, final RsHandler<T> rsh, final Object... params) throws SQLException { public static <T> T query(final Connection conn, final String sql, final RsHandler<T> rsh, final Object... params) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = StatementUtil.prepareStatement(conn, sql, params); ps = StatementUtil.prepareStatement(conn, sql, params);
return executeQuery(ps, rsh); return executeQuery(ps, rsh);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
@ -270,25 +286,21 @@ public class SqlExecutor {
* @param statementFunc 自定义{@link PreparedStatement}创建函数 * @param statementFunc 自定义{@link PreparedStatement}创建函数
* @param rsh 自定义结果集处理 * @param rsh 自定义结果集处理
* @return 结果 * @return 结果
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 5.7.17 * @since 5.7.17
*/ */
public static <T> T query(final Connection conn, final Func1<Connection, PreparedStatement> statementFunc, final RsHandler<T> rsh) throws SQLException { public static <T> T query(final Connection conn, final Func1<Connection, PreparedStatement> statementFunc, final RsHandler<T> rsh) throws DbRuntimeException {
PreparedStatement ps = null; PreparedStatement ps = null;
try { try {
ps = statementFunc.call(conn); ps = statementFunc.callWithRuntimeException(conn);
return executeQuery(ps, rsh); return executeQuery(ps, rsh);
} catch (final Exception e) {
if(e instanceof SQLException){
throw (SQLException) e;
}
throw new RuntimeException(e);
} finally { } finally {
DbUtil.close(ps); DbUtil.close(ps);
} }
} }
// -------------------------------------------------------------------------------------- Execute With PreparedStatement // -------------------------------------------------------------------------------------- Execute With PreparedStatement
/** /**
* 用于执行 INSERTUPDATE DELETE 语句以及 SQL DDL数据定义语言语句例如 CREATE TABLE DROP TABLE<br> * 用于执行 INSERTUPDATE DELETE 语句以及 SQL DDL数据定义语言语句例如 CREATE TABLE DROP TABLE<br>
* INSERTUPDATE DELETE 语句的效果是修改表中零行或多行中的一列或多列<br> * INSERTUPDATE DELETE 语句的效果是修改表中零行或多行中的一列或多列<br>
@ -299,11 +311,15 @@ public class SqlExecutor {
* @param ps PreparedStatement对象 * @param ps PreparedStatement对象
* @param params 参数 * @param params 参数
* @return 影响的行数 * @return 影响的行数
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static int executeUpdate(final PreparedStatement ps, final Object... params) throws SQLException { public static int executeUpdate(final PreparedStatement ps, final Object... params) throws DbRuntimeException {
try {
StatementUtil.fillParams(ps, params); StatementUtil.fillParams(ps, params);
return ps.executeUpdate(); return ps.executeUpdate();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -314,11 +330,15 @@ public class SqlExecutor {
* @param ps PreparedStatement对象 * @param ps PreparedStatement对象
* @param params 参数 * @param params 参数
* @return 如果执行后第一个结果是ResultSet则返回true否则返回false * @return 如果执行后第一个结果是ResultSet则返回true否则返回false
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static boolean execute(final PreparedStatement ps, final Object... params) throws SQLException { public static boolean execute(final PreparedStatement ps, final Object... params) throws DbRuntimeException {
try {
StatementUtil.fillParams(ps, params); StatementUtil.fillParams(ps, params);
return ps.execute(); return ps.execute();
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -330,11 +350,15 @@ public class SqlExecutor {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static <T> T query(final PreparedStatement ps, final RsHandler<T> rsh, final Object... params) throws SQLException { public static <T> T query(final PreparedStatement ps, final RsHandler<T> rsh, final Object... params) throws DbRuntimeException {
try {
StatementUtil.fillParams(ps, params); StatementUtil.fillParams(ps, params);
return executeQuery(ps, rsh); return executeQuery(ps, rsh);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
} }
/** /**
@ -345,9 +369,9 @@ public class SqlExecutor {
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @param params 参数 * @param params 参数
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
*/ */
public static <T> T queryAndClosePs(final PreparedStatement ps, final RsHandler<T> rsh, final Object... params) throws SQLException { public static <T> T queryAndClosePs(final PreparedStatement ps, final RsHandler<T> rsh, final Object... params) throws DbRuntimeException {
try { try {
return query(ps, rsh, params); return query(ps, rsh, params);
} finally { } finally {
@ -356,20 +380,23 @@ public class SqlExecutor {
} }
// -------------------------------------------------------------------------------------------------------------------------------- Private method start // -------------------------------------------------------------------------------------------------------------------------------- Private method start
/** /**
* 执行查询 * 执行查询
* *
* @param ps {@link PreparedStatement} * @param ps {@link PreparedStatement}
* @param rsh 结果集处理对象 * @param rsh 结果集处理对象
* @return 结果对象 * @return 结果对象
* @throws SQLException SQL执行异常 * @throws DbRuntimeException SQL执行异常
* @since 4.1.13 * @since 4.1.13
*/ */
private static <T> T executeQuery(final PreparedStatement ps, final RsHandler<T> rsh) throws SQLException { private static <T> T executeQuery(final PreparedStatement ps, final RsHandler<T> rsh) throws DbRuntimeException {
ResultSet rs = null; ResultSet rs = null;
try { try {
rs = ps.executeQuery(); rs = ps.executeQuery();
return rsh.handle(rs); return rsh.handle(rs);
} catch (final SQLException e) {
throw new DbRuntimeException(e);
} finally { } finally {
DbUtil.close(rs); DbUtil.close(rs);
} }

View File

@ -13,7 +13,6 @@ import org.junit.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.math.BigInteger; import java.math.BigInteger;
import java.sql.SQLException;
import java.util.List; import java.util.List;
/** /**
@ -23,91 +22,91 @@ import java.util.List;
*/ */
public class CRUDTest { public class CRUDTest {
private static final Db db = Db.use("test"); private static final Db db = Db.of("test");
@Test @Test
public void findIsNullTest() throws SQLException { public void findIsNullTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", "is null")); final List<Entity> results = db.findAll(Entity.create("user").set("age", "is null"));
Assert.assertEquals(0, results.size()); Assert.assertEquals(0, results.size());
} }
@Test @Test
public void findIsNullTest2() throws SQLException { public void findIsNullTest2() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", "= null")); final List<Entity> results = db.findAll(Entity.create("user").set("age", "= null"));
Assert.assertEquals(0, results.size()); Assert.assertEquals(0, results.size());
} }
@Test @Test
public void findIsNullTest3() throws SQLException { public void findIsNullTest3() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", null)); final List<Entity> results = db.findAll(Entity.create("user").set("age", null));
Assert.assertEquals(0, results.size()); Assert.assertEquals(0, results.size());
} }
@Test @Test
public void findBetweenTest() throws SQLException { public void findBetweenTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", "between '18' and '40'")); final List<Entity> results = db.findAll(Entity.create("user").set("age", "between '18' and '40'"));
Assert.assertEquals(1, results.size()); Assert.assertEquals(1, results.size());
} }
@Test @Test
public void findByBigIntegerTest() throws SQLException { public void findByBigIntegerTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", new BigInteger("12"))); final List<Entity> results = db.findAll(Entity.create("user").set("age", new BigInteger("12")));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findByBigDecimalTest() throws SQLException { public void findByBigDecimalTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("age", new BigDecimal("12"))); final List<Entity> results = db.findAll(Entity.create("user").set("age", new BigDecimal("12")));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findLikeTest() throws SQLException { public void findLikeTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("name", "like \"%三%\"")); final List<Entity> results = db.findAll(Entity.create("user").set("name", "like \"%三%\""));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findLikeTest2() throws SQLException { public void findLikeTest2() {
final List<Entity> results = db.findAll(Entity.create("user").set("name", new Condition("name", "", LikeType.Contains))); final List<Entity> results = db.findAll(Entity.create("user").set("name", new Condition("name", "", LikeType.Contains)));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findLikeTest3() throws SQLException { public void findLikeTest3() {
final List<Entity> results = db.findAll(Entity.create("user").set("name", new Condition("name", null, LikeType.Contains))); final List<Entity> results = db.findAll(Entity.create("user").set("name", new Condition("name", null, LikeType.Contains)));
Assert.assertEquals(0, results.size()); Assert.assertEquals(0, results.size());
} }
@Test @Test
public void findInTest() throws SQLException { public void findInTest() {
final List<Entity> results = db.findAll(Entity.create("user").set("id", "in 1,2,3")); final List<Entity> results = db.findAll(Entity.create("user").set("id", "in 1,2,3"));
Console.log(results); Console.log(results);
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findInTest2() throws SQLException { public void findInTest2() {
final List<Entity> results = db.findAll(Entity.create("user") final List<Entity> results = db.findAll(Entity.create("user")
.set("id", new Condition("id", new long[]{1, 2, 3}))); .set("id", new Condition("id", new long[]{1, 2, 3})));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findInTest3() throws SQLException { public void findInTest3() {
final List<Entity> results = db.findAll(Entity.create("user") final List<Entity> results = db.findAll(Entity.create("user")
.set("id", new long[]{1, 2, 3})); .set("id", new long[]{1, 2, 3}));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());
} }
@Test @Test
public void findAllTest() throws SQLException { public void findAllTest() {
final List<Entity> results = db.findAll("user"); final List<Entity> results = db.findAll("user");
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());
} }
@Test @Test
public void findTest() throws SQLException { public void findTest() {
final List<Entity> find = db.find(CollUtil.newArrayList("name AS name2"), Entity.create("user"), new EntityListHandler()); final List<Entity> find = db.find(CollUtil.newArrayList("name AS name2"), Entity.create("user"), new EntityListHandler());
Assert.assertFalse(find.isEmpty()); Assert.assertFalse(find.isEmpty());
} }
@ -123,11 +122,10 @@ public class CRUDTest {
/** /**
* 对增删改查做单元测试 * 对增删改查做单元测试
* *
* @throws SQLException SQL异常
*/ */
@Test @Test
@Ignore @Ignore
public void crudTest() throws SQLException { public void crudTest() {
// //
final Long id = db.insertForGeneratedKey(Entity.create("user").set("name", "unitTestUser").set("age", 66)); final Long id = db.insertForGeneratedKey(Entity.create("user").set("name", "unitTestUser").set("age", 66));
@ -150,7 +148,7 @@ public class CRUDTest {
@Test @Test
@Ignore @Ignore
public void insertBatchTest() throws SQLException { public void insertBatchTest() {
final User user1 = new User(); final User user1 = new User();
user1.setName("张三"); user1.setName("张三");
user1.setAge(12); user1.setAge(12);
@ -176,7 +174,7 @@ public class CRUDTest {
@Test @Test
@Ignore @Ignore
public void insertBatchOneTest() throws SQLException { public void insertBatchOneTest() {
final User user1 = new User(); final User user1 = new User();
user1.setName("张三"); user1.setName("张三");
user1.setAge(12); user1.setAge(12);
@ -192,7 +190,7 @@ public class CRUDTest {
} }
@Test @Test
public void selectInTest() throws SQLException { public void selectInTest() {
final List<Entity> results = db.query("select * from user where id in (:ids)", final List<Entity> results = db.query("select * from user where id in (:ids)",
MapUtil.of("ids", new int[]{1, 2, 3})); MapUtil.of("ids", new int[]{1, 2, 3}));
Assert.assertEquals(2, results.size()); Assert.assertEquals(2, results.size());

View File

@ -8,7 +8,6 @@ import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
import java.util.List; import java.util.List;
/** /**
@ -24,7 +23,7 @@ public class ConcurentTest {
@Before @Before
public void init() { public void init() {
db = Db.use("test"); db = Db.of("test");
} }
@Test @Test
@ -32,11 +31,7 @@ public class ConcurentTest {
for(int i = 0; i < 10000; i++) { for(int i = 0; i < 10000; i++) {
ThreadUtil.execute(() -> { ThreadUtil.execute(() -> {
final List<Entity> find; final List<Entity> find;
try {
find = db.find(CollUtil.newArrayList("name AS name2"), Entity.create("user"), new EntityListHandler()); find = db.find(CollUtil.newArrayList("name AS name2"), Entity.create("user"), new EntityListHandler());
} catch (final SQLException e) {
throw new DbRuntimeException(e);
}
Console.log(find); Console.log(find);
}); });
} }

View File

@ -20,43 +20,43 @@ import java.util.List;
public class DbTest { public class DbTest {
@Test @Test
public void queryTest() throws SQLException { public void queryTest() {
final List<Entity> find = Db.use().query("select * from user where age = ?", 18); final List<Entity> find = Db.of().query("select * from ofr where age = ?", 18);
Assert.assertEquals("王五", find.get(0).get("name")); Assert.assertEquals("王五", find.get(0).get("name"));
} }
@Test @Test
public void findTest() throws SQLException { public void findTest() {
final List<Entity> find = Db.use().find(Entity.create("user").set("age", 18)); final List<Entity> find = Db.of().find(Entity.create("ofr").set("age", 18));
Assert.assertEquals("王五", find.get(0).get("name")); Assert.assertEquals("王五", find.get(0).get("name"));
} }
@Test @Test
public void pageTest() throws SQLException { public void pageTest() {
// 测试数据库中一共4条数据第0页有3条第1页有1条 // 测试数据库中一共4条数据第0页有3条第1页有1条
final List<Entity> page0 = Db.use().page(Entity.create("user"), 0, 3); final List<Entity> page0 = Db.of().page(Entity.create("ofr"), 0, 3);
Assert.assertEquals(3, page0.size()); Assert.assertEquals(3, page0.size());
final List<Entity> page1 = Db.use().page(Entity.create("user"), 1, 3); final List<Entity> page1 = Db.of().page(Entity.create("ofr"), 1, 3);
Assert.assertEquals(1, page1.size()); Assert.assertEquals(1, page1.size());
} }
@Test @Test
public void pageTest2() throws SQLException { public void pageTest2() {
final String sql = "select * from user order by name"; final String sql = "select * from ofr order by name";
// 测试数据库中一共4条数据第0页有3条第1页有1条 // 测试数据库中一共4条数据第0页有3条第1页有1条
final List<Entity> page0 = Db.use().page( final List<Entity> page0 = Db.of().page(
sql, Page.of(0, 3)); sql, Page.of(0, 3));
Assert.assertEquals(3, page0.size()); Assert.assertEquals(3, page0.size());
final List<Entity> page1 = Db.use().page( final List<Entity> page1 = Db.of().page(
sql, Page.of(1, 3)); sql, Page.of(1, 3));
Assert.assertEquals(1, page1.size()); Assert.assertEquals(1, page1.size());
} }
@Test @Test
public void pageWithParamsTest() throws SQLException { public void pageWithParamsTest() {
final String sql = "select * from user where name = ?"; final String sql = "select * from ofr where name = ?";
final PageResult<Entity> result = Db.use().page( final PageResult<Entity> result = Db.of().page(
sql, Page.of(0, 3), "张三"); sql, Page.of(0, 3), "张三");
Assert.assertEquals(2, result.getTotal()); Assert.assertEquals(2, result.getTotal());
@ -65,59 +65,59 @@ public class DbTest {
} }
@Test @Test
public void countTest() throws SQLException { public void countTest() {
final long count = Db.use().count("select * from user"); final long count = Db.of().count("select * from ofr");
Assert.assertEquals(4, count); Assert.assertEquals(4, count);
} }
@Test @Test
public void countTest2() throws SQLException { public void countTest2() {
final long count = Db.use().count("select * from user order by name DESC"); final long count = Db.of().count("select * from ofr order by name DESC");
Assert.assertEquals(4, count); Assert.assertEquals(4, count);
} }
@Test @Test
public void findLikeTest() throws SQLException { public void findLikeTest() {
// 方式1 // 方式1
List<Entity> find = Db.use().find(Entity.create("user").set("name", "like 王%")); List<Entity> find = Db.of().find(Entity.create("ofr").set("name", "like 王%"));
Assert.assertEquals("王五", find.get(0).get("name")); Assert.assertEquals("王五", find.get(0).get("name"));
// 方式2 // 方式2
find = Db.use().findLike("user", "name", "", Condition.LikeType.StartWith); find = Db.of().findLike("ofr", "name", "", Condition.LikeType.StartWith);
Assert.assertEquals("王五", find.get(0).get("name")); Assert.assertEquals("王五", find.get(0).get("name"));
// 方式3 // 方式3
find = Db.use().query("select * from user where name like ?", "王%"); find = Db.of().query("select * from ofr where name like ?", "王%");
Assert.assertEquals("王五", find.get(0).get("name")); Assert.assertEquals("王五", find.get(0).get("name"));
} }
@Test @Test
public void findByTest() throws SQLException { public void findByTest() {
final List<Entity> find = Db.use().findBy("user", final List<Entity> find = Db.of().findBy("ofr",
Condition.parse("age", "> 18"), Condition.parse("age", "> 18"),
Condition.parse("age", "< 100") Condition.parse("age", "< 100")
); );
for (final Entity entity : find) { for (final Entity entity : find) {
StaticLog.debug("{}", entity); StaticLog.debug("{}", entity);
} }
Assert.assertEquals("unitTestUser", find.get(0).get("name")); Assert.assertEquals("unitTestofr", find.get(0).get("name"));
} }
@Test @Test
@Ignore @Ignore
public void txTest() throws SQLException { public void txTest() throws SQLException {
Db.use().tx(db -> { Db.of().tx(db -> {
db.insert(Entity.create("user").set("name", "unitTestUser2")); db.insert(Entity.create("ofr").set("name", "unitTestofr2"));
db.update(Entity.create().set("age", 79), Entity.create("user").set("name", "unitTestUser2")); db.update(Entity.create().set("age", 79), Entity.create("ofr").set("name", "unitTestofr2"));
db.del("user", "name", "unitTestUser2"); db.del("ofr", "name", "unitTestofr2");
}); });
} }
@Test @Test
@Ignore @Ignore
public void queryFetchTest() throws SQLException { public void queryFetchTest() {
// https://gitee.com/dromara/hutool/issues/I4JXWN // https://gitee.com/dromara/hutool/issues/I4JXWN
Db.use().query((conn->{ Db.of().query((conn->{
final PreparedStatement ps = conn.prepareStatement("select * from table", final PreparedStatement ps = conn.prepareStatement("select * from table",
ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY); ResultSet.CONCUR_READ_ONLY);

View File

@ -20,13 +20,8 @@ public class DerbyTest {
@BeforeClass @BeforeClass
public static void init() throws SQLException { public static void init() throws SQLException {
final Db db = Db.use(DS_GROUP_NAME); final Db db = Db.of(DS_GROUP_NAME);
try{
db.execute("CREATE TABLE test(a INTEGER, b BIGINT)"); db.execute("CREATE TABLE test(a INTEGER, b BIGINT)");
}catch (final SQLException e){
// 数据库已存在
return;
}
db.insert(Entity.create("test").set("a", 1).set("b", 11)); db.insert(Entity.create("test").set("a", 1).set("b", 11));
db.insert(Entity.create("test").set("a", 2).set("b", 21)); db.insert(Entity.create("test").set("a", 2).set("b", 21));
@ -37,14 +32,14 @@ public class DerbyTest {
@Test @Test
@Ignore @Ignore
public void queryTest() throws SQLException { public void queryTest() throws SQLException {
final List<Entity> query = Db.use(DS_GROUP_NAME).query("select * from test"); final List<Entity> query = Db.of(DS_GROUP_NAME).query("select * from test");
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
@Test @Test
@Ignore @Ignore
public void findTest() throws SQLException { public void findTest() throws SQLException {
final List<Entity> query = Db.use(DS_GROUP_NAME).find(Entity.create("test")); final List<Entity> query = Db.of(DS_GROUP_NAME).find(Entity.create("test"));
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
} }

View File

@ -15,7 +15,6 @@ import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List; import java.util.List;
/** /**
@ -27,70 +26,70 @@ import java.util.List;
public class DsTest { public class DsTest {
@Test @Test
public void defaultDsTest() throws SQLException { public void defaultDsTest() {
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void hikariDsTest() throws SQLException { public void hikariDsTest() {
DSFactory.setCurrentDSFactory(new HikariDSFactory()); DSFactory.setCurrentDSFactory(new HikariDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void druidDsTest() throws SQLException { public void druidDsTest() {
DSFactory.setCurrentDSFactory(new DruidDSFactory()); DSFactory.setCurrentDSFactory(new DruidDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void tomcatDsTest() throws SQLException { public void tomcatDsTest() {
DSFactory.setCurrentDSFactory(new TomcatDSFactory()); DSFactory.setCurrentDSFactory(new TomcatDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void beeCPDsTest() throws SQLException { public void beeCPDsTest() {
DSFactory.setCurrentDSFactory(new BeeDSFactory()); DSFactory.setCurrentDSFactory(new BeeDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void dbcpDsTest() throws SQLException { public void dbcpDsTest() {
DSFactory.setCurrentDSFactory(new DbcpDSFactory()); DSFactory.setCurrentDSFactory(new DbcpDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void c3p0DsTest() throws SQLException { public void c3p0DsTest() {
DSFactory.setCurrentDSFactory(new C3p0DSFactory()); DSFactory.setCurrentDSFactory(new C3p0DSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }
@Test @Test
public void c3p0DsUserAndPassTest() { public void c3p0DsuserAndPassTest() {
// https://gitee.com/dromara/hutool/issues/I4T7XZ // https://gitee.com/dromara/hutool/issues/I4T7XZ
DSFactory.setCurrentDSFactory(new C3p0DSFactory()); DSFactory.setCurrentDSFactory(new C3p0DSFactory());
final ComboPooledDataSource ds = (ComboPooledDataSource) ((DataSourceWrapper) DSFactory.get("mysql")).getRaw(); final ComboPooledDataSource ds = (ComboPooledDataSource) ((DataSourceWrapper) DSFactory.get("mysql")).getRaw();
@ -99,10 +98,10 @@ public class DsTest {
} }
@Test @Test
public void hutoolPoolTest() throws SQLException { public void hutoolPoolTest() {
DSFactory.setCurrentDSFactory(new PooledDSFactory()); DSFactory.setCurrentDSFactory(new PooledDSFactory());
final DataSource ds = DSFactory.get("test"); final DataSource ds = DSFactory.get("test");
final Db db = Db.use(ds); final Db db = Db.of(ds);
final List<Entity> all = db.findAll("user"); final List<Entity> all = db.findAll("user");
Assert.assertTrue(CollUtil.isNotEmpty(all)); Assert.assertTrue(CollUtil.isNotEmpty(all));
} }

View File

@ -20,11 +20,11 @@ public class FindBeanTest {
@Before @Before
public void init() { public void init() {
db = Db.use("test"); db = Db.of("test");
} }
@Test @Test
public void findAllBeanTest() throws SQLException { public void findAllBeanTest() {
final List<User> results = db.findAll(Entity.create("user"), User.class); final List<User> results = db.findAll(Entity.create("user"), User.class);
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());
@ -34,7 +34,7 @@ public class FindBeanTest {
@Test @Test
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
public void findAllListTest() throws SQLException { public void findAllListTest() {
final List<List> results = db.findAll(Entity.create("user"), List.class); final List<List> results = db.findAll(Entity.create("user"), List.class);
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());
@ -43,7 +43,7 @@ public class FindBeanTest {
} }
@Test @Test
public void findAllArrayTest() throws SQLException { public void findAllArrayTest() {
final List<Object[]> results = db.findAll(Entity.create("user"), Object[].class); final List<Object[]> results = db.findAll(Entity.create("user"), Object[].class);
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());
@ -52,13 +52,13 @@ public class FindBeanTest {
} }
@Test @Test
public void findAllStringTest() throws SQLException { public void findAllStringTest() {
final List<String> results = db.findAll(Entity.create("user"), String.class); final List<String> results = db.findAll(Entity.create("user"), String.class);
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());
} }
@Test @Test
public void findAllStringArrayTest() throws SQLException { public void findAllStringArrayTest() {
final List<String[]> results = db.findAll(Entity.create("user"), String[].class); final List<String[]> results = db.findAll(Entity.create("user"), String[].class);
Assert.assertEquals(4, results.size()); Assert.assertEquals(4, results.size());

View File

@ -4,7 +4,6 @@ import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
import java.util.List; import java.util.List;
/** /**
@ -18,8 +17,8 @@ public class H2Test {
private static final String DS_GROUP_NAME = "h2"; private static final String DS_GROUP_NAME = "h2";
@BeforeClass @BeforeClass
public static void init() throws SQLException { public static void init() {
final Db db = Db.use(DS_GROUP_NAME); final Db db = Db.of(DS_GROUP_NAME);
db.execute("CREATE TABLE test(a INTEGER, b BIGINT)"); db.execute("CREATE TABLE test(a INTEGER, b BIGINT)");
db.insert(Entity.create("test").set("a", 1).set("b", 11)); db.insert(Entity.create("test").set("a", 1).set("b", 11));
@ -29,20 +28,20 @@ public class H2Test {
} }
@Test @Test
public void queryTest() throws SQLException { public void queryTest() {
final List<Entity> query = Db.use(DS_GROUP_NAME).query("select * from test"); final List<Entity> query = Db.of(DS_GROUP_NAME).query("select * from test");
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
@Test @Test
public void findTest() throws SQLException { public void findTest() {
final List<Entity> query = Db.use(DS_GROUP_NAME).find(Entity.create("test")); final List<Entity> query = Db.of(DS_GROUP_NAME).find(Entity.create("test"));
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
@Test @Test
public void upsertTest() throws SQLException { public void upsertTest() {
final Db db=Db.use(DS_GROUP_NAME); final Db db=Db.of(DS_GROUP_NAME);
db.upsert(Entity.create("test").set("a",1).set("b",111),"a"); db.upsert(Entity.create("test").set("a",1).set("b",111),"a");
final Entity a1=db.get("test","a",1); final Entity a1=db.get("test","a",1);
Assert.assertEquals(Long.valueOf(111),a1.getLong("b")); Assert.assertEquals(Long.valueOf(111),a1.getLong("b"));

View File

@ -4,7 +4,6 @@ import org.junit.Assert;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
import java.util.List; import java.util.List;
/** /**
@ -18,8 +17,8 @@ public class HsqldbTest {
private static final String DS_GROUP_NAME = "hsqldb"; private static final String DS_GROUP_NAME = "hsqldb";
@BeforeClass @BeforeClass
public static void init() throws SQLException { public static void init() {
final Db db = Db.use(DS_GROUP_NAME); final Db db = Db.of(DS_GROUP_NAME);
db.execute("CREATE TABLE test(a INTEGER, b BIGINT)"); db.execute("CREATE TABLE test(a INTEGER, b BIGINT)");
db.insert(Entity.create("test").set("a", 1).set("b", 11)); db.insert(Entity.create("test").set("a", 1).set("b", 11));
db.insert(Entity.create("test").set("a", 2).set("b", 21)); db.insert(Entity.create("test").set("a", 2).set("b", 21));
@ -28,14 +27,14 @@ public class HsqldbTest {
} }
@Test @Test
public void connTest() throws SQLException { public void connTest() {
final List<Entity> query = Db.use(DS_GROUP_NAME).query("select * from test"); final List<Entity> query = Db.of(DS_GROUP_NAME).query("select * from test");
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
@Test @Test
public void findTest() throws SQLException { public void findTest() {
final List<Entity> query = Db.use(DS_GROUP_NAME).find(Entity.create("test")); final List<Entity> query = Db.of(DS_GROUP_NAME).find(Entity.create("test"));
Assert.assertEquals(4, query.size()); Assert.assertEquals(4, query.size());
} }
} }

View File

@ -17,16 +17,16 @@ import java.util.List;
public class MySQLTest { public class MySQLTest {
@BeforeClass @BeforeClass
@Ignore @Ignore
public static void createTable() throws SQLException { public static void createTable() {
final Db db = Db.use("mysql"); final Db db = Db.of("mysql");
db.executeBatch("drop table if exists testuser", "CREATE TABLE if not exists `testuser` ( `id` int(11) NOT NULL, `account` varchar(255) DEFAULT NULL, `pass` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8"); db.executeBatch("drop table if exists testuser", "CREATE TABLE if not exists `testuser` ( `id` int(11) NOT NULL, `account` varchar(255) DEFAULT NULL, `pass` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8");
} }
@Test @Test
@Ignore @Ignore
public void insertTest() throws SQLException { public void insertTest() {
for (int id = 100; id < 200; id++) { for (int id = 100; id < 200; id++) {
Db.use("mysql").insert(Entity.create("user")// Db.of("mysql").insert(Entity.create("user")//
.set("id", id)// .set("id", id)//
.set("name", "测试用户" + id)// .set("name", "测试用户" + id)//
.set("text", "描述" + id)// .set("text", "描述" + id)//
@ -44,7 +44,7 @@ public class MySQLTest {
@Test(expected = SQLException.class) @Test(expected = SQLException.class)
@Ignore @Ignore
public void txTest() throws SQLException { public void txTest() throws SQLException {
Db.use("mysql").tx(db -> { Db.of("mysql").tx(db -> {
final int update = db.update(Entity.create("user").set("text", "描述100"), Entity.create().set("id", 100)); final int update = db.update(Entity.create("user").set("text", "描述100"), Entity.create().set("id", 100));
db.update(Entity.create("user").set("text", "描述101"), Entity.create().set("id", 101)); db.update(Entity.create("user").set("text", "描述101"), Entity.create().set("id", 101));
if (1 == update) { if (1 == update) {
@ -57,8 +57,8 @@ public class MySQLTest {
@Test @Test
@Ignore @Ignore
public void pageTest() throws SQLException { public void pageTest() {
final PageResult<Entity> result = Db.use("mysql").page(Entity.create("user"), new Page(2, 10)); final PageResult<Entity> result = Db.of("mysql").page(Entity.create("user"), new Page(2, 10));
for (final Entity entity : result) { for (final Entity entity : result) {
Console.log(entity.get("id")); Console.log(entity.get("id"));
} }
@ -66,15 +66,15 @@ public class MySQLTest {
@Test @Test
@Ignore @Ignore
public void getTimeStampTest() throws SQLException { public void getTimeStampTest() {
final List<Entity> all = Db.use("mysql").findAll("test"); final List<Entity> all = Db.of("mysql").findAll("test");
Console.log(all); Console.log(all);
} }
@Test @Test
@Ignore @Ignore
public void upsertTest() throws SQLException { public void upsertTest() {
final Db db = Db.use("mysql"); final Db db = Db.of("mysql");
db.insert(Entity.create("testuser").set("id", 1).set("account", "ice").set("pass", "123456")); db.insert(Entity.create("testuser").set("id", 1).set("account", "ice").set("pass", "123456"));
db.upsert(Entity.create("testuser").set("id", 1).set("account", "icefairy").set("pass", "a123456")); db.upsert(Entity.create("testuser").set("id", 1).set("account", "icefairy").set("pass", "a123456"));
final Entity user = db.get(Entity.create("testuser").set("id", 1)); final Entity user = db.get(Entity.create("testuser").set("id", 1));

View File

@ -5,7 +5,6 @@ import cn.hutool.db.sql.NamedSql;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -87,17 +86,17 @@ public class NamedSqlTest {
} }
@Test @Test
public void queryTest() throws SQLException { public void queryTest() {
final Map<String, Object> paramMap = MapUtil final Map<String, Object> paramMap = MapUtil
.builder("name1", (Object)"王五") .builder("name1", (Object)"王五")
.put("age1", 18).build(); .put("age1", 18).build();
final String sql = "select * from user where name = @name1 and age = @age1"; final String sql = "select * from user where name = @name1 and age = @age1";
List<Entity> query = Db.use().query(sql, paramMap); List<Entity> query = Db.of().query(sql, paramMap);
Assert.assertEquals(1, query.size()); Assert.assertEquals(1, query.size());
// 采用传统方式查询是否能识别Map类型参数 // 采用传统方式查询是否能识别Map类型参数
query = Db.use().query(sql, new Object[]{paramMap}); query = Db.of().query(sql, new Object[]{paramMap});
Assert.assertEquals(1, query.size()); Assert.assertEquals(1, query.size());
} }
} }

View File

@ -8,8 +8,6 @@ import org.junit.Assert;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
/** /**
* Oracle操作单元测试 * Oracle操作单元测试
* *
@ -41,9 +39,9 @@ public class OracleTest {
@Test @Test
@Ignore @Ignore
public void insertTest() throws SQLException { public void insertTest() {
for (int id = 100; id < 200; id++) { for (int id = 100; id < 200; id++) {
Db.use("orcl").insert(Entity.create("T_USER")// Db.of("orcl").insert(Entity.create("T_USER")//
.set("ID", id)// .set("ID", id)//
.set("name", "测试用户" + id)// .set("name", "测试用户" + id)//
.set("TEXT", "描述" + id)// .set("TEXT", "描述" + id)//
@ -54,8 +52,8 @@ public class OracleTest {
@Test @Test
@Ignore @Ignore
public void pageTest() throws SQLException { public void pageTest() {
final PageResult<Entity> result = Db.use("orcl").page(Entity.create("T_USER"), new Page(2, 10)); final PageResult<Entity> result = Db.of("orcl").page(Entity.create("T_USER"), new Page(2, 10));
for (final Entity entity : result) { for (final Entity entity : result) {
Console.log(entity.get("ID")); Console.log(entity.get("ID"));
} }

View File

@ -13,8 +13,8 @@ public class PicTransferTest {
@Test @Test
@Ignore @Ignore
public void findTest() throws SQLException { public void findTest() {
Db.use().find( Db.of().find(
ListUtil.of("NAME", "TYPE", "GROUP", "PIC"), ListUtil.of("NAME", "TYPE", "GROUP", "PIC"),
Entity.create("PIC_INFO").set("TYPE", 1), Entity.create("PIC_INFO").set("TYPE", 1),
rs -> { rs -> {

View File

@ -1,13 +1,10 @@
package cn.hutool.db; package cn.hutool.db;
import java.sql.SQLException; import cn.hutool.core.lang.Console;
import org.junit.Assert; import org.junit.Assert;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import cn.hutool.core.lang.Console;
/** /**
* PostgreSQL 单元测试 * PostgreSQL 单元测试
* *
@ -17,9 +14,9 @@ public class PostgreTest {
@Test @Test
@Ignore @Ignore
public void insertTest() throws SQLException { public void insertTest() {
for (int id = 100; id < 200; id++) { for (int id = 100; id < 200; id++) {
Db.use("postgre").insert(Entity.create("user")// Db.of("postgre").insert(Entity.create("user")//
.set("id", id)// .set("id", id)//
.set("name", "测试用户" + id)// .set("name", "测试用户" + id)//
); );
@ -28,8 +25,8 @@ public class PostgreTest {
@Test @Test
@Ignore @Ignore
public void pageTest() throws SQLException { public void pageTest() {
final PageResult<Entity> result = Db.use("postgre").page(Entity.create("user"), new Page(2, 10)); final PageResult<Entity> result = Db.of("postgre").page(Entity.create("user"), new Page(2, 10));
for (final Entity entity : result) { for (final Entity entity : result) {
Console.log(entity.get("id")); Console.log(entity.get("id"));
} }
@ -37,8 +34,8 @@ public class PostgreTest {
@Test @Test
@Ignore @Ignore
public void upsertTest() throws SQLException { public void upsertTest() {
final Db db = Db.use("postgre"); final Db db = Db.of("postgre");
db.executeBatch("drop table if exists ctest", db.executeBatch("drop table if exists ctest",
"create table if not exists \"ctest\" ( \"id\" serial4, \"t1\" varchar(255) COLLATE \"pg_catalog\".\"default\", \"t2\" varchar(255) COLLATE \"pg_catalog\".\"default\", \"t3\" varchar(255) COLLATE \"pg_catalog\".\"default\", CONSTRAINT \"ctest_pkey\" PRIMARY KEY (\"id\") ) "); "create table if not exists \"ctest\" ( \"id\" serial4, \"t1\" varchar(255) COLLATE \"pg_catalog\".\"default\", \"t2\" varchar(255) COLLATE \"pg_catalog\".\"default\", \"t3\" varchar(255) COLLATE \"pg_catalog\".\"default\", CONSTRAINT \"ctest_pkey\" PRIMARY KEY (\"id\") ) ");
db.insert(Entity.create("ctest").set("id", 1).set("t1", "111").set("t2", "222").set("t3", "333")); db.insert(Entity.create("ctest").set("id", 1).set("t1", "111").set("t2", "222").set("t3", "333"));

View File

@ -3,8 +3,6 @@ package cn.hutool.db;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
/** /**
* 事务性数据库操作单元测试 * 事务性数据库操作单元测试
* @author looly * @author looly
@ -15,19 +13,15 @@ public class SessionTest {
@Test @Test
@Ignore @Ignore
public void transTest() { public void transTest() {
final Session session = Session.create("test"); final Session session = Session.of("test");
try {
session.beginTransaction(); session.beginTransaction();
session.update(Entity.create().set("age", 76), Entity.create("user").set("name", "unitTestUser")); session.update(Entity.create().set("age", 76), Entity.create("user").set("name", "unitTestUser"));
session.commit(); session.commit();
} catch (final SQLException e) {
session.quietRollback();
}
} }
@Test @Test
@Ignore @Ignore
public void txTest() throws SQLException { public void txTest() {
Session.create("test").tx(session -> session.update(Entity.create().set("age", 78), Entity.create("user").set("name", "unitTestUser"))); Session.of("test").tx(session -> session.update(Entity.create().set("age", 78), Entity.create("user").set("name", "unitTestUser")));
} }
} }

View File

@ -1,12 +1,9 @@
package cn.hutool.db; package cn.hutool.db;
import java.sql.SQLException; import cn.hutool.core.lang.Console;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import cn.hutool.core.lang.Console;
/** /**
* SQL Server操作单元测试 * SQL Server操作单元测试
* *
@ -17,15 +14,15 @@ public class SqlServerTest {
@Test @Test
@Ignore @Ignore
public void createTableTest() throws SQLException { public void createTableTest() {
Db.use("sqlserver").execute("create table T_USER(ID bigint, name varchar(255))"); Db.of("sqlserver").execute("create table T_USER(ID bigint, name varchar(255))");
} }
@Test @Test
@Ignore @Ignore
public void insertTest() throws SQLException { public void insertTest() {
for (int id = 100; id < 200; id++) { for (int id = 100; id < 200; id++) {
Db.use("sqlserver").insert(Entity.create("T_USER")// Db.of("sqlserver").insert(Entity.create("T_USER")//
.set("ID", id)// .set("ID", id)//
.set("name", "测试用户" + id)// .set("name", "测试用户" + id)//
); );
@ -34,8 +31,8 @@ public class SqlServerTest {
@Test @Test
@Ignore @Ignore
public void pageTest() throws SQLException { public void pageTest() {
final PageResult<Entity> result = Db.use("sqlserver").page(Entity.create("T_USER"), new Page(2, 10)); final PageResult<Entity> result = Db.of("sqlserver").page(Entity.create("T_USER"), new Page(2, 10));
for (final Entity entity : result) { for (final Entity entity : result) {
Console.log(entity.get("ID")); Console.log(entity.get("ID"));
} }

View File

@ -5,25 +5,22 @@ import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
import java.sql.SQLException;
public class UpdateTest { public class UpdateTest {
Db db; Db db;
@Before @Before
public void init() { public void init() {
db = Db.use("test"); db = Db.of("test");
} }
/** /**
* 对更新做单元测试 * 对更新做单元测试
* *
* @throws SQLException SQL异常
*/ */
@Test @Test
@Ignore @Ignore
public void updateTest() throws SQLException { public void updateTest() {
// //
final int update = db.update(Entity.create("user").set("age", 88), Entity.create().set("name", "unitTestUser")); final int update = db.update(Entity.create("user").set("age", 88), Entity.create().set("name", "unitTestUser"));