Spring事务
JdbcTemplate
Spring 提供的JDBC模板
- tx.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="root"></property>
<property name="password" value="Gepoint"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mqtt"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="initialPoolSize" value="10"></property>
<property name="maxPoolSize" value="100"></property>
<property name="minPoolSize" value="10"></property>
<property name="maxIdleTime" value="30"></property>
</bean>
</beans>
- MyTx.java
public class MyTx {
ApplicationContext context = new ClassPathXmlApplicationContext("tx.xml");
@Test
public void test01() throws SQLException {
DataSource dataSource = context.getBean("datasource",ComboPooledDataSource.class);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select * from user";
RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
List<User> list = jdbcTemplate.query(sql,rowMapper);
System.out.println("hello"+list +"\n" + jdbcTemplate.getMaxRows());
}
}
总结:第一步加入容器管理,第二步配置数据源,第三步,使用JdbcTemplate管理连接
备注:jdbcTemplate可以通过bean注入
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="datasource"></constructor-arg>
</bean>
Spring Transaction事务
<context:component-scan base-package="amrom.dao,amrom.service"></context:component-scan>
<!-- 事务管理器 -->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="comboPooledDataSource"></property>
</bean>
<!-- 开启注解 -->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" />
@Transactional
public void checkout(User user) {
userDao.query();
userDao.update(user);
}