JDBC数据库通用DAO
时间:2022-03-13 22:54
1.数据库连接池
package org.dave.common.database;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ResourceBundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
* 数据库连接池
* @author David Day
public final class DatabaseConnectionPool {
private static final Logger LOG = LoggerFactory.getLogger(DatabaseConnectionPool.class);
private static final ResourceBundle BUNDLE = ResourceBundle.getBundle("connection");
private static final String DRIVER = "driver";
private static final String URL = "url";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String MAX_CONNECTION = "max_connection";
private static BoneCP pool;
* 开启连接池
public static void startup() {
try {
Class.forName(BUNDLE.getString(DRIVER));
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl(BUNDLE.getString(URL));
config.setUsername(BUNDLE.getString(USERNAME));
config.setPassword(BUNDLE.getString(PASSWORD));
config.setMaxConnectionsPerPartition(Integer.parseInt(BUNDLE.getString(MAX_CONNECTION)));
pool = new BoneCP(config);
} catch (Exception e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
* 关闭连接池
public static void shutdown() {
pool.shutdown();
* @return 数据库连接
public static Connection getConnection() {
try {
return pool.getConnection();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
2.数据库异常
package org.dave.common.database;
* 数据库异常
* @author David Day
@SuppressWarnings("serial")
public class DatabaseException extends RuntimeException {
public DatabaseException(Throwable cause) {
super(cause);
3.事务控制
package org.dave.common.database;
import java.sql.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* 数据库事务
* @author David Day
public class DatabaseTransaction {
* 日志工具
*/
private static final Logger LOG = LoggerFactory.getLogger(DatabaseTransaction.class);
* 数据库连接
private Connection conn;
* 实例化一个默认连接的事务
public DatabaseTransaction() {
this(DatabaseConnectionPool.getConnection());
* 实例化一个默认连接的事务
* @param isOpenTrans 是否打开事务
*/
public DatabaseTransaction(boolean isOpenTrans) throws DatabaseException {
this(DatabaseConnectionPool.getConnection(), isOpenTrans);
* 实例化一个默认连接的事务
* @param conn 数据库连接
*/
public DatabaseTransaction(Connection conn) {
this.conn = conn;
* 实例化一个默认连接的事务
* @param conn 数据库连接
* @param isOpenTrans 是否打开事务
*/
public DatabaseTransaction(Connection conn, boolean isOpenTrans) throws DatabaseException {
this.conn = conn;
setAutoCommit(!isOpenTrans);
* @return 数据库连接
*/
public Connection getConnection() {
return conn;
* 设置是否自动提交
* @param autoCommit 自动提交
* @throws DatabaseException
*/
private void setAutoCommit(boolean autoCommit) throws DatabaseException {
try {
conn.setAutoCommit(autoCommit);
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
* 开始事务
* @throws DatabaseException
*/
public void begin() throws DatabaseException {
setAutoCommit(false);
* @return 是否打开事务
* @throws DatabaseException
*/http://www.huiyi8.com/css3/
public boolean isBegin() throws DatabaseException {
try {
return !conn.getAutoCommit();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
/**
* 提交
* @throws DatabaseException
*/
public void commit() throws DatabaseException {
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
* 回滚
* @throws DatabaseException
*/
public void rollback() throws DatabaseException {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e)
* 关闭连接
* @throws DatabaseException
*/
public void close() throws DatabaseException {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
* @return 连接是否关闭
* @throws DatabaseException
*/
public boolean isClose() throws DatabaseException {
try {
return conn.isClosed();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DatabaseException(e);
4.通用数据模型
package org.dave.common.database;
import java.io.Serializable;
@SuppressWarnings("serial")
public abstract class DataModel implements Serializable { }
5.结果转换器
package org.dave.common.database.convert;
import java.sql.ResultSet;
import java.sql.SQLException;
* 结果映射器
* @author David Day
public interface ResultConverter<T> {
* 映射
* @param rs 结果集
* @return 映射结果
* @throws SQLException
*/
public T convert(ResultSet rs) throws SQLException ;
6.通用dao
package org.dave.common.database.access;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.dave.common.database.convert.ResultConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* 数据存取类
* @author David Day
*/
public abstract class DataAccess {
* 日志工具
*/
private static final Logger LOG = LoggerFactory.getLogger(DataAccess.class);
* 数据库连接
private Connection conn;
* @param conn 数据库连接
protected DataAccess(Connection conn) {
this.conn = conn;
* 插入数据
* @param sql
* @param generatedKeysConverter 主键映射
* @param params
* @return 主键
* @throws DataAccessException
*/
protected <T> T insert(String sql, ResultConverter<T> generatedKeysConverter, Object... params) throws DataAccessException {
try {
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
setParameters(pstmt, params);
executeUpdate(pstmt);
ResultSet rs = pstmt.getGeneratedKeys();
nextResult(rs);
return convertResult(rs, generatedKeysConverter);
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 更新数据
* @param sql
* @param params
* @return 影响行数
* @throws DataAccessException
*/
protected int update(String sql, Object... params) throws DataAccessException {
return executeUpdate(getPreparedStatement(sql, params));
* 查询单个结果
* @param <T>
* @param sql
* @param converter
* @param params
* @return
protected <T> T queryForObject(String sql, ResultConverter<T> converter, Object... params) {
ResultSet rs = executeQuery(sql, params);
if (nextResult(rs)) {
return convertResult(rs, converter);
} else {
return null;
* 查询结果列表
* @param <T>
* @param sql
* @param converter
* @param params
* @return
protected <T> List<T> queryForList(String sql, ResultConverter<T> converter, Object... params) {
ResultSet rs = executeQuery(sql, params);
List<T> list = new ArrayList<T>();
while (nextResult(rs)) {
list.add(convertResult(rs, converter));
return list;
* @param sql SQL语句
* @return 预编译声明
private PreparedStatement getPreparedStatement(String sql, Object... params) throws DataAccessException {
PreparedStatement pstmt = getPreparedStatement(sql);
setParameters(pstmt, params);
return pstmt;
* @param sql SQL语句
* @return 预编译声明
*/
private PreparedStatement getPreparedStatement(String sql) throws DataAccessException {
try {
return conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 为预编译声明传入参数
* @param pstmt 预编译声明
* @param params 参数
* @throws DataAccessException
private void setParameters(PreparedStatement pstmt, Object... params) throws DataAccessException {
try {
for (int i = 0; i < params.length; i++) {
pstmt.setObject(i + 1, params[i]);
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 执行更新操作
* @param pstmt
* @return 影响行数
* @throws DataAccessException
private int executeUpdate(PreparedStatement pstmt) throws DataAccessException {
try {
return pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 执行查询操作
* @param pstmt 预编译声明
* @return 结果集
* @throws DataAccessException
private ResultSet executeQuery(PreparedStatement pstmt) throws DataAccessException {
try {
return pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 执行查询操作
* @param sql SQL语句
* @param params 参数
* @return 结果集
* @throws DataAccessException
private ResultSet executeQuery(String sql, Object... params) throws DataAccessException {
return executeQuery(getPreparedStatement(sql, params));
* 移动到下一行记录
* @param rs 结果集
* @return 是否有下一行记录
* @throws DataAccessException
*/
private boolean nextResult(ResultSet rs) throws DataAccessException {
try {
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
* 映射
* @param rs 结果集
* @return 映射结果
* @throws DataAccessException
*/
private <T> T convertResult(ResultSet rs, ResultConverter<T> converter) throws DataAccessException {
try {
return converter.convert(rs);
} catch (SQLException e) {
e.printStackTrace();
LOG.error(e.getMessage(), e);
throw new DataAccessException(e);
7.数据库存取异常
package org.dave.common.database.access;
* 数据库存取异常
* @author David Day
@SuppressWarnings("serial")
public class DataAccessException extends RuntimeException {
public DataAccessException(Throwable cause) {
super(cause);
JDBC数据库通用DAO,布布扣,bubuko.com