Spring封装的jdbc调用,很基本、简单的方式。
<bean id = "transactionManager2"
class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref="dataSource"/>
</bean>
<!--1:配置一个JdbcTemplate实例,并将这个“共享的”,“安全的”实例注入到不同的DAO类中去-->
<bean id = "jdbcTemplate"
class = "org.springframework.jdbc.core.JdbcTemplate">
<property name = "dataSource" ref="dataSource"/>
</bean>
<bean id = "easyDao"
class = "com.xxx.orm.EasyDao">
<property ref="jdbcTemplate"/>
</bean>
<!--利用了拦截器的原理。-->
<bean
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property>
<ref bean="transactionManager2" />
</property>
<!-- 配置事务属性 -->
<property>
<props>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="operate*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property>
<list>
<value>*Dao*</value><!--只是为了测试,一般为service-->
</list>
</property>
<property>
<list>
<value>transactionInterceptor</value>
</list>
</property>
</bean>
代码:
public class EasyDao{
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
protected class CloudosInstallationRowMapper implements RowMapper {
public T mapRow(ResultSet rs, int rowNum)
throws SQLException {
CloudosInstallation ci = new CloudosInstallation();
ci.setId(rs.getInt("id"));
return (T) ci;
}
}
public List query3(String sql)
{
return jdbcTemplate.query(sql, new CloudosInstallationRowMapper());