SpringBoot_扩展数据库操作_DBUtils

本文详细介绍了如何在SpringBoot项目中整合DBUtils和C3P0,实现高效数据库操作。通过配置pom.xml依赖,定义C3P0属性,并创建Db实用类,展示了查询、更新等数据库操作的实现方式。

SpringBoot_扩展数据库操作_DBUtils

依赖pom.xml

	<dependency>
		<groupId>commons-dbutils</groupId>
		<artifactId>commons-dbutils</artifactId>
	</dependency>
	<dependency>
		<groupId>c3p0</groupId>
		<artifactId>c3p0</artifactId>
		<version>0.9.1.2</version>
	</dependency>

配置类

//pingruan.base.c3p0.data.use-ext-data=true
//pingruan.base.c3p0.data.driver-class=com.mysql.jdbc.Driver
//pingruan.base.c3p0.data.jdbc-url=jdbc:mysql://192.168.164.100:3306/manage-a?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
//pingruan.base.c3p0.data.user=root
//pingruan.base.c3p0.data.password=qwe123

配置源码

@Component
@ConfigurationProperties(prefix="pingruan.base.c3p0.data")
@Data
public class C3p0Properties {
	private String useExtData = "false";
	private String driverClass;
	private String jdbcUrl;
	private String user;
	private String password;
	private int initialPoolSize = 10;
	private int minPoolSize = 5;
	private int maxPoolSize = 20;
}
/**
 * 获取数据库连接
 *
 * @author vander
 * @date 2018年11月26日
 */
public class Db {
	
	private static final QueryRunner runner = new QueryRunner();
	private static ComboPooledDataSource ds = null;
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	
	Db(C3p0Properties c3p0){
		try {
			ds = new ComboPooledDataSource();
			ds.setDriverClass(c3p0.getDriverClass());
			ds.setJdbcUrl(c3p0.getJdbcUrl());
			ds.setUser(c3p0.getUser());
			ds.setPassword(c3p0.getPassword());
			ds.setInitialPoolSize(c3p0.getInitialPoolSize());
			ds.setMinPoolSize(c3p0.getMinPoolSize());
			ds.setMaxPoolSize(c3p0.getMaxPoolSize());
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	
	/**
	 * 获取连接
	 * 
	 * @return
	 * @throws SQLException
	 */
	private Connection getConnection() throws SQLException {
		Connection conn = threadLocal.get();
		if (null == conn) {
			conn = getDataSource().getConnection();
			threadLocal.set(conn);
		}
		return conn;
	}

	/**
	 * 开启事务
	 */
	private void startTransaction() {
		try {
			Connection conn = threadLocal.get();
			if (null == conn) {
				conn = getConnection();
				threadLocal.set(conn);
			}
			conn.setAutoCommit(false);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 事务提交
	 */
	private void commit() {
		try {
			Connection conn = threadLocal.get();
			if (conn != null) {
				conn.commit();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 事务回滚
	 */
	private void rollback() {
		try {
			Connection conn = threadLocal.get();
			if (conn != null) {
				conn.rollback();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 释放连接
	 */
	private void close() {
		try {
			Connection conn = threadLocal.get();
			if (conn != null) {
				conn.close();
				threadLocal.remove();
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获取数据源
	 * 
	 * @return
	 */
	private DataSource getDataSource() {
		return ds;
	}


	/**
	 * 查询(返回Array结果)
	 * @param sql
	 * @param params
	 * @return
	 */
	public Object[] queryArray(String sql, Object... params) {
		Object[] result = null;
		try {
			result = runner.query(getConnection(), sql, new ArrayHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询(返回ArrayList结果)
	 * @param sql
	 * @param params
	 * @return
	 */
	public List<Object[]> queryArrayList(String sql, Object... params) {
		List<Object[]> result = null;
		try {
			result = runner.query(getConnection(), sql, new ArrayListHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询(返回Map结果)
	 * @param sql
	 * @param params
	 * @return
	 */
	public Map<String, Object> queryMap(String sql, Object... params) {
		Map<String, Object> result = null;
		try {
			result = runner.query(getConnection(), sql, new MapHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询(返回MapList结果)
	 * @param sql
	 * @param params
	 * @return
	 */
	public List<Map<String, Object>> queryMapList(String sql, Object... params) {
		List<Map<String, Object>> result = null;
		try {
			result = runner.query(getConnection(), sql, new MapListHandler(), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/* 查询(返回Bean结果) */
	public <T> T queryBean(Class<T> cls, Map<String, String> map, String sql,
			Object... params) {
		T result = null;
		try {
			if (map != null) {
				result = runner.query(getConnection(), sql, new BeanHandler<T>(cls, new BasicRowProcessor(new BeanProcessor(map))),
						params);
			} else {
				result = runner.query(getConnection(), sql, new BeanHandler<T>(cls), params);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询(返回BeanList结果)
	 * @param cls
	 * @param map
	 * @param sql
	 * @param params
	 * @return
	 */
	public <T> List<T> queryBeanList(Class<T> cls, Map<String, String> map, String sql,
			Object... params) {
		List<T> result = null;
		try {
			if (map != null) {
				result = runner.query(getConnection(), sql,
						new BeanListHandler<T>(cls, new BasicRowProcessor(new BeanProcessor(map))), params);
			} else {
				result = runner.query(getConnection(), sql, new BeanListHandler<T>(cls), params);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询指定列名的值(单条数据)
	 * @param column
	 * @param sql
	 * @param params
	 * @return
	 */
	public <T> T queryColumn(String column, String sql, Object... params) {
		T result = null;
		try {
			result = runner.query(getConnection(), sql, new ScalarHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询指定列名的值(多条数据)
	 * @param column
	 * @param sql
	 * @param params
	 * @return
	 */
	public <T> List<T> queryColumnList(String column, String sql, Object... params) {
		List<T> result = null;
		try {
			result = runner.query(getConnection(), sql, new ColumnListHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 查询指定列名对应的记录映射
	 * @param column
	 * @param sql
	 * @param params
	 * @return
	 */
	public <T> Map<T, Map<String, Object>> queryKeyMap(String column, String sql,
			Object... params) {
		Map<T, Map<String, Object>> result = null;
		try {
			result = runner.query(getConnection(), sql, new KeyedHandler<T>(column), params);
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}

	/**
	 * 更新(包括UPDATE、INSERT、DELETE,返回受影响的行数)
	 * @param sql
	 * @param params
	 * @return
	 */
	public int update( String sql, Object... params) {
		int result = 0;
		try {
			startTransaction();
			result = runner.update(getConnection(), sql, params);
			commit();
		} catch (SQLException e) {
			rollback();
			e.printStackTrace();
		}finally {
			close();
		}
		return result;
	}
}

//@Autowired
//Db db;
/**
 * 扩展数据源
 * 
 *
 * @author vander
 * @date 2018年11月26日
 */
@Configuration
@ConditionalOnProperty(value="pingruan.base.c3p0.data.use-ext-data",havingValue="true")
public class DbConfig {
	
	@Autowired
	C3p0Properties c3p0Properties;
	
	@Bean
	public Db dbs() {
		return new Db(c3p0Properties);
	}

}
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/  :: Spring Boot ::   (v3.3.4) {"timestamp":"2025-10-14 11:31:09.508","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"j.c.s.s.Application","MethodName":"logStarting","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"Starting Application using Java 17.0.12 with PID 19080 (D:\SY22BNEC31\新しいフォルダー (5)\shelf-batch-sshb0051-application-develop\build\bin\main started by sycnc in D:\SY22BNEC31\新しいフォルダー (5)\shelf-batch-sshb0051-application-develop\build)"} {"timestamp":"2025-10-14 11:31:09.513","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"j.c.s.s.Application","MethodName":"logStartupProfileInfo","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"No active profile set, falling back to 1 default profile: "default""} {"timestamp":"2025-10-14 11:31:09.937","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.b.c.c.a.BatchRegistrar","MethodName":"registerBeanDefinitions","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"Finished Spring Batch infrastructure beans configuration in 5 ms."} {"timestamp":"2025-10-14 11:31:10.271","severity":"WARNING","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker","MethodName":"postProcessAfterInitialization","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"Bean 'jobRegistry' of type [org.springframework.batch.core.configuration.support.MapJobRegistry] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying). Is this bean getting eagerly injected into a currently created BeanPostProcessor [jobRegistryBeanPostProcessor]? Check the corresponding BeanPostProcessor declaration and its dependencies."} {"timestamp":"2025-10-14 11:31:10.362","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"c.z.h.HikariDataSource","MethodName":"getConnection","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"HikariPool-1 - Starting..."} {"timestamp":"2025-10-14 11:31:10.584","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"c.z.h.p.HikariPool","MethodName":"checkFailFast","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"HikariPool-1 - Added connection conn0: url=jdbc:h2:mem:instantdb user=SA"} {"timestamp":"2025-10-14 11:31:10.586","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"c.z.h.HikariDataSource","MethodName":"getConnection","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"HikariPool-1 - Start completed."} {"timestamp":"2025-10-14 11:31:10.650","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.b.c.r.s.JobRepositoryFactoryBean","MethodName":"afterPropertiesSet","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"No database type set, using meta data indicating: H2"} {"timestamp":"2025-10-14 11:31:10.668","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.b.c.l.s.SimpleJobLauncher","MethodName":"afterPropertiesSet","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"No TaskExecutor has been set, defaulting to synchronous executor."} {"timestamp":"2025-10-14 11:31:11.120","severity":"WARNING","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.c.a.AnnotationConfigApplicationContext","MethodName":"refresh","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbUtils': Injection of autowired dependencies failed"} {"timestamp":"2025-10-14 11:31:11.120","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"c.z.h.HikariDataSource","MethodName":"close","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"HikariPool-1 - Shutdown initiated..."} {"timestamp":"2025-10-14 11:31:11.123","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"c.z.h.HikariDataSource","MethodName":"close","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"HikariPool-1 - Shutdown completed."} {"timestamp":"2025-10-14 11:31:11.131","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.b.a.l.ConditionEvaluationReportLogger","MethodName":"logMessage","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":" Error starting ApplicationContext. To display the condition evaluation report re-run your application with 'debug' enabled."} {"timestamp":"2025-10-14 11:31:11.148","severity":"ERROR","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"o.s.b.SpringApplication","MethodName":"reportFailure","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"Application run failed"} org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbUtils': Injection of autowired dependencies failed at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:515) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1439) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:975) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:971) ~[spring-context-6.1.13.jar:6.1.13] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625) ~[spring-context-6.1.13.jar:6.1.13] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) [spring-boot-3.3.4.jar:3.3.4] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) [spring-boot-3.3.4.jar:3.3.4] at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) [spring-boot-3.3.4.jar:3.3.4] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1363) [spring-boot-3.3.4.jar:3.3.4] at jp.co.sej.ssc.Application.main(Application.java:63) [main/:?] Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'spring.datasource.driver-class-name' in value "${spring.datasource.driver-class-name}" at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180) ~[spring-core-6.1.13.jar:6.1.13] at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126) ~[spring-core-6.1.13.jar:6.1.13] at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239) ~[spring-core-6.1.13.jar:6.1.13] at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210) ~[spring-core-6.1.13.jar:6.1.13] at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:200) ~[spring-context-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:964) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1374) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1353) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:785) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:768) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:145) ~[spring-beans-6.1.13.jar:6.1.13] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:509) ~[spring-beans-6.1.13.jar:6.1.13] ... 15 more {"timestamp":"2025-10-14 11:31:11.155","severity":"ERROR","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"j.c.s.s.Application","MethodName":"main","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"異常 exitCode : 100 Exception : org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbUtils': Injection of autowired dependencies failed"} {"timestamp":"2025-10-14 11:31:11.155","severity":"INFO","logging.googleapis.com/labels":{"zwb_log":"batch","ProcessName":"shelf-batch-sshb0051-application","ProcessID":"19080","ThreadID":"main","ClassName":"j.c.s.s.Application","MethodName":"main","JOBID":"","DAGID":"","TASKID":"","REQID":""},"message":"終了"}
最新发布
10-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值