personServiceImpl.java
package jdbc.transaction.annotation; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service(value="personService") public class PersonServiceImpl implements PersonService { @Resource(name="personDao") private PersonDao personDao; @Transactional(readOnly=false) public void savePerson() { this.personDao.savePerson(); } }
personDaoImpl.java
package jdbc.transaction.annotation; import javax.annotation.Resource; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; @Repository(value="personDao") public class PersonDaoImpl implements PersonDao { @Resource(name="jdbcTemplate") private JdbcTemplate jdbcTemplate; @Override public void savePerson() { this.jdbcTemplate.execute("insert into Person values (4, '艾瑟顿')"); } }
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:component-scan base-package="jdbc.transaction.annotation"></context:component-scan> <tx:annotation-driven transaction-manager="transactionManager" />
<!-- 定义事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置数据库连接池 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3399/db" /> <property name="username" value="root" /> <property name="password" value="3333456" /> </bean> </beans>
浙公网安备 33010602011771号