spring框架学习之路(二)-进阶技能(1)-数据库连接池和事务管理

来源:互联网 发布:淘宝有店铺怎么登陆 编辑:程序博客网 时间:2024/06/07 02:57

1.定义Spring的数据库连接池

  <context:property-placeholder location="classpath:db.properties"/>    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">     <property name="driverClass" value="${db_driver}"></property>     <property name="jdbcUrl" value="${db_url}"></property>     <property name="user" value="${db_username}"></property>     <property name="initialPoolSize" value="${db_init_connections}"></property>     <property name="maxPoolSize" value="${db_max_connection}"></property>     <property name="password" value="${db_password}"></property>  </bean>   <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">     <property name="dataSource" ref="dataSource"></property>  </bean>

——–在其中db.properties文件中配置数据库的链接信息, (注意导入响应的数据库驱动包以及c3p0包)
JdbcTemplate类相当于一个BaseDao的代理类

db.properties文件格式:db_driver=com.mysql.jdbc.Driverdb_url=jdbc:mysql://localhost/testdb_init_connections=30db_max_connection=60db_username=rootdb_password=123

在main方法中直接getBean获取JdbcTemplate类对象,即可使用!
**

2.spring事务的处理

首先声明事务管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">    <property name="dataSource" ref="dataSource"></property>  </bean>

1)基于注解
—-在目标方法上添加注解

@Transactional[(propagation=Propagation.REQUIRED,readOnly=true,timeout=20000)]

—-让事务声明注解生效

<tx:annotation-driven transaction-manager="transactionManager">

2)基于XML文件
不需要添加注解

 <tx:advice id="transactionAdvice" transaction-manager="transactionManager">     <tx:attributes><tx:method name="buss*" propagation="REQUIRED"/>            <tx:method name="add*" propagation="REQUIRED"/>            <tx:method name="update*" propagation="REQUIRED"/>            <tx:method name="insert*" propagation="REQUIRED"/>            <tx:method name="find" propagation="REQUIRED"/></tx:attributes>  </tx:advice>     <aop:config>     <aop:pointcut expression="execution(* com.neusoft..*(..))" id="txPoint"/>     <aop:advisor advice-ref="transactionAdvice" pointcut-ref="txPoint"/>  </aop:config>

附录:
propagation事务传播
1)REQUIRED_NEW:生成新的事务,如果存在之前的事务,之前的事务挂起
2)REQUIRED:如果当前存在事务,就是加入,如果没有创建
3)SUPPORTS:如果有事务加入,那么以非事务的方式运行

阅读全文
0 0
原创粉丝点击