- import javax.sql.DataSource;
- import org.springframework.jdbc.core.*;
- import org.springframework.transaction.*;
- import org.springframework.dao.*;
- public class bookDAO{
- private DataSource dataSource;// 依赖注入 dataSource ,管理数据库
- private PlatformTransationManager transactionManager;// 依赖注入管理事务
- public void setDataSource(DataSource dataSource){
- this.dataSource=dataSource;
- }
- public void setTransactionManager(PlatformTransationManager transactionManager){
- this. transactionManager= transactionManager;
- }
- public int create(String msg){
- JdbcTemplate jdbcTemplate=new JdbcTemplate(dataSource);
- jdbcTemplate.update(“INSERT INFO book VALUES(1,’gf’,’Mastering Spring’)”);
- }
- }
- "XML" _code
- <beans>
- <bean id="dataSource" class="org.springframework.jdbc.datasource.
- DriverManagerDataSource”">
- <!— 使用SQL Server 数 据 库 à
- <property name="driverClassName">
- <value>com.microsoft.jdbc.sqlserver.SQLServerDriver</value>
- </property>
- <property name="url">
- <value>jdbc:Microsoft:sqlserver://localhost:1433/stdb</value>
- </property>
- <property name="name">
- <value>admin</value>
- </property>
- <property name="msg">
- <value>admin</value>
- </property>
- </bean>
- <bean id="transactionManager" class="org.springframework.jdbc.
- datasource.DataSourceTransactionManager">
- <property name="dataSource">
- <ref bean="dataSource"></ref>
- </property>
- </bean>
- <!— DAO-->
- <bean id="bookDAO" class="com.bookDAO">
- <property name="dataSource">
- <ref bean="dataSource"/>
- </property>
- <property name="”transactionManager”">
- <ref bean="”transactionManager”">
- </property>
- </bean>
- <bean id="bookDAOProxy" class="”org.springframework.transaction.interceptor.
- Transation.ProxyFactoryBean”">
- <property name="transacionManager">
- <ref bean="transacionMaganer"/>
- </property>
- <property name="target">
- <ref bean="bookDAO"/>
- </property>
- <property name="transactionAttributes">
- <props>
- <prop key="create">PROPAGATION_REQUIRED</prop>
- </props>
- </property>
- </bean>
- </beans>