1. 配置数据源
<bean id = "dataSource" class="org.apach.connons.dbcp.BasicDataSource" destory-method="close">
<property name = driverClassName value="org.gtj.mm.mysql.Driver"/>
<property name = "url" value = "jdbc:mysql://localhost:8090/testjdbc?useUnicod=true&characterEncoding=UTF-8"/>
<property name = "username" value = "sa"/>
<property name = "password" value = "password"/>
</bean>
2. 配置事务。
配置事务时,需要在xml配置文件中引入用于事务声明的tx命名空间。事务的配置方式有两种,基于xml的配置和基于注释的配置
基于注释的配置
1. 注入事务管理器
<bean id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name = "dataSource" ref = "dataSource"/></bean>
2.引入tx命名空间
xmlns:tx = "http://www.springframework.org./schama/tx"
3.配置注解驱动器
<tx:annotaion-driver transaction-manager = "txManager"/>
但是现在我们一般用JdbcTemplete这个类来进行数据的操作,吧JdbcTemplete作为业务类的数据源<bean id = "transcService" class = "com.web.service.TranscServiceImpl"><property name = "dataSource" ref= "dataSource"/></bean>
然后再业务方法里就可以直接用jdbcTempelete来进行数据库德操作了, 如果我们想要对业务类的方法进行事务管理,直接在类上加注释就可以了
@Transaction public class TranscServiceImpl{
private JdbcTemplete jdbcTemplete;
public TranscServiceImpl(DataSource dataSource) {
this.JdbcTemplete = New JdbcTemplete(dataSource)
}
public void save(Person person) {
jdbcTemplete.update("insert into user(name) value(?), new Object[]{person.getName()}, new int[]{java.sql.Types.VARCHAR}");
}
}