一.JDBCTemplate
导入的jar
//创建连接池
DriverManagerDataSource dmd=
new
DriverManagerDataSource();
//往连接池里面设置4大参数
dmd.setDriverClassName(
"com.mysql.jdbc.Driver"
);
dmd.setUrl(
"jdbc:mysql:///myspring03"
);
dmd.setUsername(
"root"
);
dmd.setPassword(
"root"
);
//创建jdbcTemplate模板
JdbcTemplate template =
new
JdbcTemplate();
//将连接池设置到模板中
template.setDataSource(dmd);
=====================
-->
引入外部文件:
==============
==================
1.1.5Spring的事务管理:
声明事务管理在xml中的配置:(基于AOPxml的配置)
<
context:property-placeholder
location
=
"classpath:db.properties"
/>
<
bean
id
=
"dataSource"
class
=
"com.mchange.v2.c3p0.ComboPooledDataSource"
>
<
property
name
=
"driverClass"
value
=
"${jdbc.driver}"
/>
<
property
name
=
"jdbcUrl"
value
=
"${jdbc.url}"
/>
<
property
name
=
"user"
value
=
"${jdbc.user}"
/>
<
property
name
=
"password"
value
=
"${jdbc.password}"
>
property
>
bean
>
<
bean
id
=
"accountService"
class
=
"cn.itcast.demo3.AccountServiceImpl"
>
<
property
name
=
"accountDao"
ref
=
"accountDao"
>
property
>
bean
>
<
bean
id
=
"accountDao"
class
=
"cn.itcast.demo3.AccountDaoImpl"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
>
property
>
bean
>
<
bean
id
=
"transactionManager"
class
=
"org.springframework.jdbc.datasource.DataSourceTransactionManager"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
>
property
>
bean
>
<
tx:advice
id
=
"txAdvice"
transaction-manager
=
"transactionManager"
>
<
tx:attributes
>
<
tx:method
name
=
"transf"
/>
tx:attributes
>
tx:advice
>
<
aop:config
>
<
aop:pointcut
expression
=
"execution(* cn.itcast.demo3.AccountService+.*(..))"
id
=
"mypointcut"
/>
<
aop:advisor
advice-ref
=
"txAdvice"
pointcut-ref
=
"mypointcut"
/>
aop:config
>
步骤:
1>导包 aop tx
2>在xml中配置
- 配置数据源
- 声明目标类,持久层的类。并且在持久层中注入数据源,目的是Dao类继承JdbcDaoSupport。此类帮我们拿到模板,直接注入数据源即可
- 注册事务管理器。事务管理器中注入数据源!目的是获得连接,开启事务
- 定义增强。事务管理的 : 事务里面的属性
- 定义Aop的设置
第二步
:
注解事务
:
第三步:
在
Service
上使用注解
@Transactional
* 注解中有属性值:
* isolation
* propagation
* readOnly
=====================
<
context:property-placeholder
location
=
"classpath:db.properties"
/>
<
bean
id
=
"dataSource"
class
=
"com.mchange.v2.c3p0.ComboPooledDataSource"
>
<
property
name
=
"driverClass"
value
=
"${jdbc.driver}"
/>
<
property
name
=
"jdbcUrl"
value
=
"${jdbc.url}"
/>
<
property
name
=
"user"
value
=
"${jdbc.user}"
/>
<
property
name
=
"password"
value
=
"${jdbc.password}"
>
property
>
bean
>
<
bean
id
=
"accountService"
class
=
"cn.itcast.demo4.AccountServiceImpl"
>
<
property
name
=
"accountDao"
ref
=
"accountDao"
>
property
>
bean
>
<
bean
id
=
"accountDao"
class
=
"cn.itcast.demo4.AccountDaoImpl"
>
<
property
name
=
"dataSource"
ref
=
"dataSource"
>
property
>
bean
>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name="dataSource" ref="dataSource" >property>
bean >
<tx:annotation-driven transaction-manager="transactionManager" />
在目标类上加上
public
class
AccountServiceImpl
implements
AccountService {