10、Spring+JDBC组合开发
使用Spring+JDBC集成步骤如下:
<!-- 1 配置dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<!-- & 转义字符 其实就是代表一个& -->
<property name="url" value="jdbc:mysql://localhost:3306/itcastdb?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--2 配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置dao层 -->
<bean id="accountDao" class="com.itcast.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
上面使用了Apache组织的dbcp数据源,我们需要把
lib\jakarta-commons下的commons-dbcp.jar和commons-pool.jar加入类路下。
**********************************************
配置数据源(详细)
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/itcastdb?useUnicode=true&characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="123456"/> <!-- 连接池启动时的初始值 --> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于该值时,连接池就会预申请一些连接,以避免洪峰来时再申请而造成的性能开销 --> <property name="minIdle" value="1"/> </bean>
上面使用了Apache组织的dbcp数据源,我们需要把lib\jakarta-commons下的commons-dbcp.jar和commons-pool.jar加入类路下。
******************************************************
使用JdbcTemplate进行insert/update/delete操作
public class AccountDaoImpl implements AccountDao { private JdbcTemplate jdbcTemplate; //声明JDBC模板 //添加 public void saveAccount(Account account) throws Exception { jdbcTemplate.update("insert into account(accountid,balance) values(?,?)“, new Object[]{account.getAccountid(),account.getBalance()}, new int[]{java.sql.Types.VARCHAR,java.sql.Types.DOUBLE}); } //更新 public void updateAccount(Account account) throws Exception { String sql="update account set balance=? where accountid=?"; jdbcTemplate.update(sql, new Object[]{account.getBalance(),account.getAccountid()}, new int[]{java.sql.Types.DOUBLE,java.sql.Types.VARCHAR}); } //删除 public void deleteAccount(String accountid) throws Exception { String sql="delete from account where accountid=?"; jdbcTemplate.update(sql, new Object[]{accountid}, new int[]{java.sql.Types.VARCHAR} ); } }
**************************************************************
使用JdbcTemplate获取一条记录
/获取一条记录 public Account getAccount(String accountid) { Account account=(Account)jdbcTemplate.queryForObject( "select accountid,balance from account where accountid=?", new Object[]{accountid}, new int[]{java.sql.Types.VARCHAR}, new RowMapperImpl()); return account; } //接口实现类 public class RowMapperImpl implements RowMapper { public Object mapRow(ResultSet rs, int rowNum) throws SQLException { System.out.println(" rowNum " + rowNum); Account account=new Account(); account.setAccountid(rs.getString("accountid")); account.setBalance(rs.getDouble("balance")); return account; } } //获取多条记录 public List<Account> getAccounts() throws Exception { String sql="select * from account order by accountid"; RowMapper rowMapper=new RowMapper(){ public Object mapRow(ResultSet rs, int rowNum) throws SQLException { Account account=new Account(); account.setAccountid(rs.getString("accountid")); account.setBalance(rs.getDouble("balance")); return account; } }; return jdbcTemplate.query(sql,rowMapper); }
******************************************************************************
Spring 事务管理
事务的传播特性:
REQUIRED 业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到该事务,否则为自己创建一个新的事务
NOT_SUPPORTED 声明方法不需要事务。如果方法没有关联到一个事务,容器不会为它开启事务。如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行
REQUIRESNEW 属性表明不管是否存在事务,业务方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务会被挂起,新的事务会被创建,直到方法执行结束,新事务才算结束,原先的事务才会恢复执行
MANDATORY 该属性指定业务方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果业务方法在没有事务的环境下调用,容器就会抛出例外。
SUPPORTS 这一事务属性表明,如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分。如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行
Never 指定业务方法绝对不能在事务范围内执行。如果业务方法在某个事务中执行,容器会抛出例外,只有业务方法没有关联到任何事务,才能正常执行
NESTED 如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按REQUIRED属性执行.它使用了一个单独的事务, 这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效
事务的隔离级别:
不同的隔离级别采用不同的锁类型来实现,在四种隔离级别中,Serializable的隔离级别最高,Read Uncommited的隔离级别最低。
大多数据库默认的隔离级别为Read Commited,如SqlServer
当然也有少部分数据库默认的隔离级别为Repeatable_Read ,如Mysql,
Oracle数据库支持READ COMMITTED和SERIALIZABLE两种事务隔离性级别,不支持READ UNCOMMITTED和REPEATABLE READ这两种隔离性级别。虽然SQL标准定义的默认事务隔离性级别是SERIALIZABLE,但是Oracle数据库默认使用的事务隔离性级别却是READ COMMITTED.
***************************************************************
在spring配置文件中引入用于声明事务的tx命名空间
<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/tx http://www.springframework.org/schema/tx/spring-tx-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">
</beans>
Spring+JDBC组合开发(配置事务xml方式)
<!--1 配置dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcastdb" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--2 配置JDBC模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--3 配置jdbc的事务管理器 -->
<bean id="dataSourceTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--4 配置通知 -->
<tx:advice id="advice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--5 配置切面 -->
<aop:config>
<aop:pointcut id="accountservice" expression="execution(*com.itcast.service..*.*(..))"/>
<aop:advisor advice-ref="advice" pointcut-ref="accountservice"/>
</aop:config>
<!-- 配置dao层 -->
<bean id="accountDao" class="com.itcast.dao.impl.AccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<bean id="inaccountDao" class="com.itcast.dao.impl.InAccountDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
<!-- 配置业务层 -->
<bean id="inAccountService" class="com.itcast.service.impl.InAccountServiceImpl">
<property name="accountDao" ref="accountDao" />
<property name="inAccountDao" ref="inaccountDao" />
</bean>
****************************************************************
配置事务注解方式
Bean.xml文件中配置如下
<!--1 启用spring的自动扫描功能-->
<context:component-scan base-package="com.itcast"></context:component-scan>
<!--2 配置dbcp数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/itcastdb" />
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--3 配置jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4 配置jdbc事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--5 采用@Transactional注解方式使用事务 -->
<tx:annotation-driven transaction-manager="txManager" />