几种数据源的配置方式

article/2025/9/17 21:38:53

目录

 

1.c3p0配置方式

2.dbcp配置方式

3.DriverManagerDataSource配置方式

4.HikariDataSource配置方式

5.多数据源整合(编程式事务)


1.c3p0配置方式

lib:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.test" /><aop:aspectj-autoproxy /><context:property-placeholder location="classpath:config/jdbc.properties" /><bean id="parent" class="com.mchange.v2.c3p0.ComboPooledDataSource" abstract="true"><property name="driverClass" value="${jdbc.driverClassName}" /><property name="jdbcUrl" value="${jdbc.url}" /><!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3 --><property name="initialPoolSize" value="10" /><!-- 连接池中保留的最大连接数。默认值:15 --><property name="maxPoolSize" value="20" /><!-- 连接池中保留的最小连接数,默认为:3 --><property name="minPoolSize" value="2" /><!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。默认值: 0 --><property name="maxIdleTime" value="60" /><!-- 当连接池连接耗尽时,客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒。默认: 0 --><property name="checkoutTimeout" value="3000" /><!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 --><property name="acquireIncrement" value="2" /><!--定义在从数据库获取新连接失败后重复尝试的次数。默认值: 30 ;小于等于0表示无限次--><property name="acquireRetryAttempts" value="0" /><!--重新尝试的时间间隔,默认为:1000毫秒--><property name="acquireRetryDelay" value="1000" /><!--关闭连接时,是否提交未提交的事务,默认为false,即关闭连接,回滚未提交的事务 -->   <property name="autoCommitOnClose" value="false" /><!--c3p0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用。默认值: null --><property name="automaticTestTable" value="Test" /><!--如果为false,则获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常,但是数据源仍有效保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认: false-->   <property name="breakAfterAcquireFailure" value="false" />  <!--每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->   <property name="idleConnectionTestPeriod" value="60" />  <!--c3p0全局的PreparedStatements缓存的大小。如果maxStatements与maxStatementsPerConnection均为0,则缓存不生效,只要有一个不为0,则语句的缓存就能生效。如果默认值: 0-->   <property name="maxStatements" value="100" />  <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。默认值: 0 -->   <property name="maxStatementsPerConnection" value="0" />  </bean><bean id="dataSource" parent="parent"><property name="user" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:mapper/*.xml" /></bean><bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean id="userDAO" class="com.test.dao.UserDAO"><property name="sqlSession" ref="sqlSessionTemplate" /></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 配置事务增强处理bean,指定事务管理器 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><!-- 用于配置详细的事务语义 --><tx:attributes><!-- 所有以get和find开头的方法都是read-only的 --><tx:method name="get*" read-only="true"/><tx:method name="find*" read-only="true"/><!-- 其他方法使用默认的事务设置 --><tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/></tx:attributes></tx:advice><!-- AOP配置的元素 --><aop:config proxy-target-class="true"><!-- 配置一个切入点,匹配com.test.service及其子包下所有以Impl结尾的类里、所有方法的执行 --><aop:pointcut id="myPointcut" expression="execution(* com.test.service..*.*(..))"/><!-- 指定在txAdvice切入点应用txAdvice事务增强处理 --><aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/><aop:aspect ref="myAspect"><aop:around pointcut-ref="myPointcut" method="myPointCut"/></aop:aspect></aop:config><!-- 加载切面 --><bean id="myAspect" class="com.test.aspect.myAspect" />
</beans>

2.dbcp配置方式

lib:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.test" /><aop:aspectj-autoproxy /><context:property-placeholder location="classpath:config/jdbc.properties" /><bean id="parent" class="org.apache.commons.dbcp.BasicDataSource" abstract="true"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><!-- 定义初始连接数   --><property name="initialSize" value="10" /><!-- 定义最大连接数 --><property name="maxActive" value="20"/><!-- 定义最大空闲 --><property name="maxIdle" value="20"/><!-- 定义最小空闲 --><property name="minIdle" value="1"/><!-- 定义最长等待时间  --><property name="maxWait" value="60000"/></bean><bean id="dataSource" parent="parent"><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:mapper/*.xml" /></bean><bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean id="userDAO" class="com.test.dao.UserDAO"><property name="sqlSession" ref="sqlSessionTemplate" /></bean><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 配置事务增强处理bean,指定事务管理器 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><!-- 用于配置详细的事务语义 --><tx:attributes><!-- 所有以get和find开头的方法都是read-only的 --><tx:method name="get*" read-only="true"/><tx:method name="find*" read-only="true"/><!-- 其他方法使用默认的事务设置 --><tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/></tx:attributes></tx:advice><!-- AOP配置的元素 --><aop:config proxy-target-class="true"><!-- 配置一个切入点,匹配com.test.service及其子包下所有以Impl结尾的类里、所有方法的执行 --><aop:pointcut id="myPointcut" expression="execution(* com.test.service..*.*(..))"/><!-- 指定在txAdvice切入点应用txAdvice事务增强处理 --><aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/><aop:aspect ref="myAspect"><aop:around pointcut-ref="myPointcut" method="myPointCut"/></aop:aspect></aop:config><!-- 加载切面 --><bean id="myAspect" class="com.test.aspect.myAspect" />
</beans>

myAspect.java

package com.test.aspect;import java.util.Arrays;import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.test.domain.UserInfo;public class myAspect {private static final Logger logger = LoggerFactory.getLogger(myAspect.class);public Object myPointCut(ProceedingJoinPoint jp) throws Throwable {//执行的方法String method = jp.getSignature().getName();logger.info("执行的方法名称:" + method);//入参Object[] args = jp.getArgs();if (args != null && args.length > 0) {if (args[0] == UserInfo.class) {logger.info(method + "方法入参:" + args[0].toString());} else {logger.info(method + "方法入参:" + Arrays.toString(args));}}Object rvt = jp.proceed();return rvt;}
}

3.DriverManagerDataSource配置方式

lib:

BaseDAO.java

package com.tgb.dao;import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;public class BaseDAO {@Autowired@Qualifier("sqlSession")protected SqlSession sqlSession;public void setSqlSession(SqlSession sqlSession) {this.sqlSession = sqlSession;}public SqlSession getSqlSession() {return sqlSession;}
}

ServiceAspect.java

package com.tgb.aspect;import java.util.Arrays;import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;@Aspect
public class ServiceAspect {public Logger logger = Logger.getLogger(ServiceAspect.class);@Around(value="execution(public * com.tgb.service..*Impl.*(..))")public Object processAspect(ProceedingJoinPoint jp) throws Throwable {String method = jp.getSignature().getName();logger.info("执行的方法名称:" + method);String method1 = jp.getThis().getClass().getName() + "|" + jp.getSignature().getName();logger.info("执行的方法名称1:" + method1);String inputArgs = toString(jp.getArgs());logger.info(method + "方法的入参:" + inputArgs);String inputArgs1 = Arrays.toString(jp.getArgs());logger.info(method + "方法的入参1:" + inputArgs1);//		Class<?> returnType = ((MethodSignature)jp.getSignature()).getReturnType();
//		logger.info(method + "方法返回值类型:" + returnType);//执行目标方法Object rvt = jp.proceed();//可以改变入参
//		Object rvt = jp.proceed(new String[]{"被改变的参数"});return rvt;}public String toString(Object[] args) {StringBuilder sb = new StringBuilder();for (Object arg : args) {sb.append(arg).append(",");}return sb.toString();}
}

sqlmap-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><mappers><mapper resource="com/tgb/dao/mapper/userMapper.xml"/></mappers>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p"xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.tgb" /><aop:aspectj-autoproxy /><!-- 1.首先配置数据源:DriverManagerDataSource --><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/ibatis" /><property name="username" value="root" /><property name="password" value="123456" /></bean><!-- 2.配置mybatis的SqlSession工厂:SqlSessionFactoryBean dataSource:引用数据源 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><!-- <property name="mapperLocations" value="com/tgb/dao/mapper/*.xml" /> -->  <!-- 这样配置单元测试不会报错,但是将项目部署到tomcat的时候会提示找不到文件 --><property name="configLocation" value="classpath:spring/sqlmap-config.xml" /></bean><!-- 3.配置sqlSession --><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><!-- 事务配置 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" />	</bean><!-- 配置事务增强处理器 --><tx:advice id="txAdvice" transaction-manager="transactionManager"><!-- 用于配置详细的事务语义 --><tx:attributes><!-- 所有以get和find开头的方法都是只读的 --><tx:method name="get*" read-only="true"/><tx:method name="find*" read-only="true"/><!-- 其他方法使用默认的事务设置 --><tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/></tx:attributes></tx:advice><!-- AOP配置的元素 --><aop:config proxy-target-class="true"><!-- 配置一个切入点,匹配com.tgb.service及其子包下所有以Impl结尾的类里、所有方法的执行 --><aop:pointcut expression="execution(public * com.tgb.service..*Impl.*(..))" id="myPointcut"/><!-- 指定在txAdvice切入点应用txAdvice事务增强处理 --><aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"/></aop:config><!-- 加载切面 --><bean class="com.tgb.aspect.ServiceAspect" />
</beans>

4.HikariDataSource配置方式

lib:

sqlmap-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="cacheEnabled" value="true" /><setting name="lazyLoadingEnabled" value="true" /><setting name="aggressiveLazyLoading" value="false"/>
<!-- 		<setting name="logImpl" value="STDOUT_LOGGING" /> --></settings>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.test" /><aop:aspectj-autoproxy /><context:property-placeholder location="classpath:config/jdbc.properties" /><bean id="hikaripBase" class="com.zaxxer.hikari.HikariDataSource" abstract="true"><property name="connectionTestQuery" value="SELECT 1" /><!-- 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒 --><property name="connectionTimeout" value="5000" /><!-- 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟 --><property name="idleTimeout" value="6000" /><!-- 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL wait_timeout参数(show variables like '%timeout%';) --><property name="maxLifetime" value="25" /><!-- 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count) --><property name="maximumPoolSize" value="50" /><property name="minimumIdle" value="2" /></bean><bean id="dataSource" parent="hikaripBase"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="jdbcUrl" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="configLocation" value="classpath:spring/sqlmap-config.xml"/><property name="mapperLocations"><list><value>classpath:mapper/**/*.xml</value></list></property></bean><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean id="userDAO" class="com.test.dao.UserDAO"><property name="sqlSession" ref="sqlSession" /></bean><bean id="userManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><bean id="transactionManager" class="org.springframework.data.transaction.ChainedTransactionManager"><constructor-arg><list><ref bean="userManager"/></list></constructor-arg></bean><tx:annotation-driven transaction-manager="transactionManager"/><bean class="com.test.aspect.myAspect" /></beans>

5.多数据源整合(编程式事务)

lib:

sqlmap-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><setting name="cacheEnabled" value="true" /><setting name="lazyLoadingEnabled" value="true" /><setting name="aggressiveLazyLoading" value="false"/>
<!-- 		<setting name="logImpl" value="STDOUT_LOGGING" /> --></settings>
</configuration>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  xmlns:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"  xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.1.xsd    http://www.springframework.org/schema/mvc    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-3.0.xsd"><context:component-scan base-package="com.test" /><aop:aspectj-autoproxy /><context:property-placeholder location="classpath:config/jdbc.properties" /><bean id="atomikosDataSource" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close" abstract="true"><property name="xaDataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlXADataSource" /><property name="testQuery" value="SELECT 1" /><property name="minPoolSize" value="1" /><property name="maxPoolSize" value="100" /><property name="maintenanceInterval" value="25" /><property name="borrowConnectionTimeout" value="10" /></bean><bean id="dataSource" parent="atomikosDataSource"><property name="uniqueResourceName" value="user" /><property name="xaProperties"><props><prop key="user">${jdbc.username}</prop><prop key="password">${jdbc.password}</prop><prop key="URL">${jdbc.url}</prop></props></property></bean><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="configLocation" value="classpath:spring/sqlmap-config.xml"/><property name="mapperLocations"><list><value>classpath:mapper/**/*.xml</value></list></property></bean><bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"><constructor-arg index="0" ref="sqlSessionFactory" /></bean><bean id="userDAO" class="com.test.dao.UserDAO"><property name="sqlSession" ref="sqlSession" /></bean><!-- 配置事务 --><!-- 分布式事务 --><bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close"><property name="forceShutdown" value="true" /></bean><bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp"><property name="transactionTimeout" value="3600" /></bean><bean id="springTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"><property name="transactionManager" ref="atomikosTransactionManager" /><property name="userTransaction" ref="atomikosUserTransaction" /><!-- 必须设置,否则程序出现异常 JtaTransactionManager does not support custom isolation levels by default --><property name="allowCustomIsolationLevels" value="true" /></bean><!-- 事务模板 --><bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate"><property name="transactionManager" ref="springTransactionManager" /><property name="isolationLevelName" value="ISOLATION_DEFAULT" /><property name="propagationBehaviorName" value="PROPAGATION_REQUIRED" /></bean><bean class="com.test.aspect.myAspect" /></beans>

UserServiceImpl.java

package com.test.service;import java.util.List;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;import com.test.api.UserService;
import com.test.dao.UserDAO;
import com.test.domain.UserInfo;@Service
public class UserServiceImpl implements UserService {private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);@Autowiredprivate TransactionTemplate transactionTemplate;@Autowiredprivate UserDAO userDAO;public void addUser(final UserInfo user) {transactionTemplate.execute(new TransactionCallback<Boolean>() {@Overridepublic Boolean doInTransaction(TransactionStatus status) {try {userDAO.addUser(user);logger.info("操作user_account表成功,userId:" + user.getUserId());userDAO.addUserInfo(user);logger.info("操作user_info表成功,id:" + user.getId());
//					System.out.println("测试:" + (5/0));} catch (Exception e) {e.printStackTrace();status.setRollbackOnly();throw e;}return true;}});}public void deleteUser(final Integer userId) {transactionTemplate.execute(new TransactionCallback<Boolean>() {@Overridepublic Boolean doInTransaction(TransactionStatus status) {try {Integer count = userDAO.deleteUser(userId);logger.info("删除user_account表操作成功,userId:" + userId + ",更新数量:" + count);count = userDAO.deleteFromUserInfo(userId);logger.info("删除user_info表成功,userId:" + userId + ",更新数量:" + count);} catch (Exception e) {e.printStackTrace();status.setRollbackOnly();throw e;}return true;}});}public void updateUser(final UserInfo user) {transactionTemplate.execute(new TransactionCallback<Boolean>() {@Overridepublic Boolean doInTransaction(TransactionStatus status) {try {String userName = user.getUserName();if (userName != null && !"".equals(userName)) {Integer userNameCount = userDAO.getUserByUserName(userName);if (userNameCount > 0) {logger.info("用户名已近存在。。。");return false;}}Integer count = userDAO.updateUser(user);logger.info("更新user_account表用户成功,userId:" + user.getUserId() + ",更新条数:" + count);Integer count1 = userDAO.updateUserInfo(user);logger.info("更新user_info表成功,user_id:" + user.getUserId() + ",更新数量:" + count1);} catch (Exception e) {e.printStackTrace();status.setRollbackOnly();throw e;}return true;}});}public void getUsers() {List<UserInfo> users = userDAO.getUsers();if (users != null && users.size() > 0) {for (UserInfo userInfo : users) {logger.info(userInfo.toString());}}}public void getUserByUserId(Integer userId) {UserInfo userInfo = userDAO.getUserByUserId(userId);if (userInfo != null) {logger.info(userInfo.toString());}}}

http://chatgpt.dhexx.cn/article/XtnwZeop.shtml

相关文章

多数据源配置-springBoot

前言 这里展示的是springBoot项目双数据源的配置&#xff0c;为了增加一定的代表性&#xff0c;这里采用两个不同的数据库Orcale和Mysql作为数据源。 依赖 <!-- orcale驱动包 --> <dependency><groupId>com.oracle.database.jdbc</groupId><arti…

若依多数据源配置

1.修改application-druid.yml文件&#xff0c;这里使用mysql数据源&#xff0c;分别有ry-vue、ry-test1、ry-test2三个数据库。 2.修改DataSourceType类&#xff08;MASTER主库&#xff0c;SLAVE、LOGIN两个从库&#xff09;。 3.修改DruidConfig类。 以上配置完成后&#xff0…

如何配置数据源

(一&#xff09;官网 Spring Initializrhttps://start.spring.io/ &#xff08;二&#xff09;各依赖 &#xff08;三&#xff09;打印一下数据源 &#xff08;四&#xff09;查看有哪些bean &#xff08;五&#xff09;不用spring boot自己配置bean 1、数据源相关 • DataSou…

SpringBoot 之数据源配置

文章目录 市面上的几种数据源比对SpringBoot自动装配DataSource原理HiKariCP 数据源配置Druid 数据源配置SpringBoot集成Druid连接池Druid 多数据源配置&#xff08;不同Mapper操作不同数据源&#xff09;HikariCP 多数据源动态配置 springboot2.0整合druid&#xff0c;以及spr…

P值 卡方值

P值&#xff1a; P值即概率&#xff0c;反映某一事件发生的可能性大小。 不同的P数值所表达的含义也是不一样的。 统计学根据显著性检验方法所得到的P 值&#xff0c;一般以P < 0.05 为有统计学差异&#xff0c; P<0.01 为有显著统计学差异&#xff0c;P<0.001为有…

Python数据挖掘学习6卡方检验

1.定义&#xff1a;一种用途很广的计数资料的假设检验方法。它属于非参数检验的范畴&#xff0c;主要是比较两个及两个以上样本率( 构成比&#xff09;以及两个分类变量的关联性分析。 2.基本思想&#xff1a;统计样本的实际观测值与理论推断值之间的偏离程度&#xff0c;实际…

python scipy 密度函数 分位数 累计函数计算p值 卡方检验 t检验 F检验 假设检验 AB实验 显著性检验

AB实验&#xff1a; 1. 人均类->t检验 # 计算t值 def get_t(x):# 遍历看x需要几次的显著性检验。可能有多个实验组&#xff0c;需要一对一检验x1 x[x.分组.astype(str)1].iloc[0] # 对照组&#xff0c;组号固定为1&#xff0c;转为Series格式for i in x[x.分组.astype(st…

卡方检验c语言算法,R语言 | 卡方检验(Chi-squaretest)

卡方检验在计数资料中的应用,包括推断两个总体率或构成比之间有无差别、多个总体率或构成比之间有无差别、多个样本率间的多重比较、两个分类变量之间有无关联性、多维列联表的分析和频数分布拟合优度的卡方检验。选自:周支瑞老师 下面分别介绍计数资料怎么进行卡方检验。 目…

SPSS篇—卡方检验

今天依旧跟大家分享一个在SPSS中使用率比较高的分析方法&#xff1a;卡方检验。 在开始做分析之前&#xff0c;我们需要明白两件事情&#xff1a;卡方检验是什么&#xff1f;一般用来干什么&#xff1f;我们只有充分了解分析方法以后才能够正确的使用它。 卡方检验在百科中的…

四格表卡方检验.医学统计实例详解-医学统计助手★卡方检验,t检验,F检验,秩和检验,方差分析

四格表卡方检验是医学统计学中常用的一种方法&#xff0c;用于确定两个分类变量之间是否存在关联。在医学研究中&#xff0c;四格表卡方检验被广泛应用于研究疾病和治疗方法之间的关联&#xff0c;以及预测疾病发展的风险因素。 四格表卡方检验基于一个二维表格&#xff0c;也…

卡方检验四格表怎么做_运用SPSS进行医学诊断数据的Kappa一致性检验 ——【杏花开医学统计】...

杏花开生物医药统计 一号在手,统计无忧! 关 注 运用SPSS进行医学诊断数据的 Kappa一致性检验 关键词:SPSS、 Kappa 导读 在医学诊断试验中,经常会遇到将待评价的诊断实验方法的诊断结果与金标准的诊断结果进行比较的情况,或者是将两种不同的诊断方法用于同一样本的诊断结果…

卡方检验四格表怎么做_等级变量的假设检验怎么做?

作者&#xff1a;丁点helper 来源&#xff1a;丁点帮你 今天&#xff0c;我们讲等级变量的假设检验。首先&#xff0c;回顾一下&#xff0c;什么叫等级变量&#xff0c;也称有序变量。 一般而言&#xff0c;等级变量属于分类变量(如上)的一种&#xff0c;与之相对的就是无序变…

Pearson卡方该如何计算?

一、Pearson卡方 Pearson卡方可用研究定类和定类数据的差异&#xff0c;比如性别和是否吸烟之间的差异关系。 二、分析 SPSSAU通用方法里面的‘交叉&#xff08;卡方&#xff09;’研究方法默认使用Pearson卡方&#xff0c;并且提供百分比按行或者按列两种方式。如下图&…

卡方检验概述

前言、什么是卡方检验 卡方检验是一种用途很广的计数资料的假设检验方法。它属于非参数检验的范畴&#xff0c;主要是比较两个及两个以上样本率( 构成比&#xff09;以及两个分类变量的关联性分析。其根本思想就是在于比较理论频数和实际频数的吻合程度或拟合优度问题。 它在…

Python计算卡方值

Python代码 import numpy as np from scipy.stats import chi2_contingencyd np.array([[2, 1, 1, 0, 276], [9, 7, 4, 2, 258]]) print(chi2_contingency(d)) # 第一个值为卡方值&#xff0c; # 第二个值为P值&#xff0c; # 第三个值为自由度&#xff0c; # 第四个为与原数…

卡方检验值转换为P值

卡方检验作为一种常见的假设检验&#xff0c;在统计学中的地位是显而易见的&#xff0c;如果你还不太清楚可以参看这篇博文:卡方检验用于特征选择&#xff0c;写的非常的浅显易懂&#xff0c;如果你还想再扩展点卡方检验方面的知识&#xff0c;可以参看这篇博文卡方检验基础&am…

别错过,卡方检验实用总结!

通常情况下&#xff0c;卡方检验是研究分类数据与分类数据之间关系的分析方法&#xff0c;如性别和是否戴隐形眼镜之间的关系。卡方检验通常会涉及卡方值和P值两个名词术语。卡方值与P值有对应关系&#xff0c;P值小于0.05则说明有差异存在&#xff0c;即性别与是否戴隐形眼镜之…

【数据分析与数据挖掘】四、多因子与复合分析(上)

这一章内容&#xff1a;属性与属性之间常见的联系。 理论铺垫&#xff1a; 假设检验与方差检验&#xff1b;相关系数&#xff1a;皮尔逊、斯皮尔曼&#xff1b;回归&#xff1a;线性回归&#xff1b;PCA与奇异值分解&#xff1b; 1.假设检验 概念&#xff1a;做出一个假设&…

2020淘宝双11超级星秀猫怎么踢人 最强星秀猫怎么退出队伍

2020年的天猫双十一的喵币活动是叫—超级星秀猫&#xff0c;还是一个养猫的活动&#xff0c;不过是可以组队的&#xff0c;有的朋友是想把临时的人踢出队伍或者是自己离开队伍&#xff0c;但是不知道怎么操作&#xff0c;下面就来为大家详细的介绍一下。 1、踢人&#xff1a;今…

单点登录 ( 踢人模式 )

这是最终效果图 实现用户账号在别处登陆&#xff0c;踢出上个已经登陆的账号 单点登陆基本原理: 项目Demo结构 项目 demo 源码 https://github.com/610627597/TestDemo