1. JdbcTemplate使用:
(1):jar包导入:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
(2):XML配置:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/spring_day3?serverTimezone=GMT&useSSL=false"></property>
<property name="username" value="root"></property>
<property name="password" value="d2430414211"></property>
</bean>
(3):使用:
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jt = context.getBean("jdbcTemplate", JdbcTemplate.class);
jt.execute("insert into account(name, money) values('ddd', 1000)");
}
(4)JdbcDaoSupport:使用后可以减少Dao实现类中对于JdbcTemplate对象的重复使用(xml中DAO注入DataSource)。
2. Srping事务控制XML配置:
(1):配置事务控制器:
<!--事务控制器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
(2):配置事务通知:
<!--事务的通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager"></tx:advice>
(3):配置事务的属性:
①:事务的属性:
——isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
——propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
——read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
——timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
——rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
——no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
②:XML配置:
<!--事务的属性-->
<tx:attributes>
<tx:method name="transfer" propagation="REQUIRED" read-only="false"></tx:method>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
</tx:attributes>
(4):配置切面:
<aop:config>
<aop:pointcut id="pt1" expression="execution(* cn.xupt.service.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
</aop:config>
(5):注解配置:
<!--事务控制器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<!--随后在需要的地方配上@Transactional注解-->