Day3:Spring-JDBC、事务管理

jdbc的编程:
 *  获取链接  

 *   Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url,username,password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeUpdate(sql)/executeQuery(sql); List<Person> persoList = new ArrayList<Person>(); while(rs.next()){ Person person = new Person(); person.setPid(rs.getLong("pid")); person.setPname(rs.getString("pname")); personList.add(person); } * jdbc的编程特点: 固定代码+可变参数=模板模式
Spring配置数据库的连接池有两种方式
第一种方式
<bean id="dataSource" destroy-method="close"                
    class="org.apache.commons.dbcp.BasicDataSource">   <property name="driverClassName" value="com.mysql.jdbc.Driver" />   <property name="url" value="jdbc:mysql://localhost:3306/vijay" />   <property name="username" value="root" />   <property name="password" value="root" /> </bean> 第二种方式 * 导入属性文件   <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     <property name="locations">
      <value>classpath:com/foo/jdbc.properties</value>     </property>   </bean> * <bean id="dataSource1" destroy-method="close"
      class="org.apache.commons.dbcp.BasicDataSource">     <property name="driverClassName" value="${driverClassName}" />     <property name="url" value="${url}" />     <property name="username" value="${username}"/>     <property name="password" value="${password}"/>   </bean>
spring声明式事务处理配置文件的思路
<aop:config>
  //切入点表达式
      表达式应该把目标类包括进去
  //通知
  <aop:advisor advice-ref="tx" pointcut-ref="perform"/>
</aop:config>
通知:
<tx:advice id="tx" transaction-manager="transactionManager"
  >
   <tx:attributes>
      <tx:method name="save*" propagation="REQUIRED"/>
   </tx:attributes>
</tx>
事务管理器:
<bean id="transactionManager"
   class="DataSourceTransactionManager">
    <property name="dataSource">
       <ref bean="dataSource"/>
      </property>
</bean>

程序员做的事情
注入service
 <bean id="personService" class="PersonServiceImpl">
     <property name="personDao">
        <ref bean="personDao"/>
     </property>

 </bean>
注入dao
<bean id="personDao" class="PersonDaoImpl">
   <property name="dataSource">
        <ref bean="dataSource"/>
    </property>
</bean>
dataSource:
  *  导入properties文件
   <bean
  class="PropertyPlaceholderConfigurer">
  <property name="locations">
   <value>
classpath:cn/itcast/spring0401/jdbc/transaction/xml/jdbc.properties
   </value>
  </property>
 </bean>
 *  <bean id="dataSource"..>
  
原文地址:https://www.cnblogs.com/vijay/p/3526780.html