![JAR search and dependency download from the Maven repository](/logo.png)
com.jchanghong.db.DaoTemplate Maven / Gradle / Ivy
The newest version!
package com.jchanghong.db;
import com.jchanghong.core.collection.CollectionUtil;
import com.jchanghong.core.util.StrUtil;
import com.jchanghong.db.ds.DSFactory;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
/**
* 数据访问层模板
* 此模板用于简化对指定表的操作,简化的操作如下:
* 1、在初始化时指定了表名,CRUD操作时便不需要表名
* 2、在初始化时指定了主键,某些需要主键的操作便不需要指定主键类型
* @author Looly
*
*/
public class DaoTemplate {
/** 表名 */
protected String tableName;
/** 本表的主键字段,请在子类中覆盖或构造方法中指定,默认为id */
protected String primaryKeyField = "id";
/** SQL运行器 */
protected Db db;
//--------------------------------------------------------------- Constructor start
/**
* 构造,此构造需要自定义SqlRunner,主键默认为id
* @param tableName 数据库表名
*/
public DaoTemplate(String tableName) {
this(tableName, (String)null);
}
/**
* 构造,使用默认的池化连接池,读取默认配置文件的空分组,适用于只有一个数据库的情况
* @param tableName 数据库表名
* @param primaryKeyField 主键字段名
*/
public DaoTemplate(String tableName, String primaryKeyField) {
this(tableName, primaryKeyField, DSFactory.get());
}
public DaoTemplate(String tableName, DataSource ds) {
this(tableName, null, ds);
}
/**
* 构造
* @param tableName 表名
* @param primaryKeyField 主键字段名
* @param ds 数据源
*/
public DaoTemplate(String tableName, String primaryKeyField, DataSource ds) {
this(tableName, primaryKeyField, Db.use(ds));
}
/**
* 构造
* @param tableName 表名
* @param primaryKeyField 主键字段名
* @param db Db对象
*/
public DaoTemplate(String tableName, String primaryKeyField, Db db) {
this.tableName = tableName;
if(StrUtil.isNotBlank(primaryKeyField)){
this.primaryKeyField = primaryKeyField;
}
this.db = db;
}
//--------------------------------------------------------------- Constructor end
//------------------------------------------------------------- Add start
/**
* 添加
* @param entity 实体对象
* @return 插入行数
* @throws SQLException SQL执行异常
*/
public int add(Entity entity) throws SQLException {
return db.insert(fixEntity(entity));
}
/**
* 添加
* @param entity 实体对象
* @return 主键列表
* @throws SQLException SQL执行异常
*/
public List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy