一、Spring JDBC

一、使用Spring JDBC准备步骤

  导入spring  jdbc jar包

  导入数据库驱动包

  导入c3p0连接池

二、测试Spring JDBC进行CRUD

  1、传统获取JdbcTemplate

//一般方法获取配置spring jdbc 模板
    public JdbcTemplate getTemp() throws Exception 
    {
        //使用C3P0连接池
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        //配置数据库连接参数
        dataSource.setJdbcUrl("jdbc:oracle:thin:@//localhost:1521/mydb");
        dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
        dataSource.setUser("");
        dataSource.setPassword("");
        //将连接池交给模板
        JdbcTemplate jt=new JdbcTemplate();
        jt.setDataSource(dataSource);
        return jt;
    }

  2、Spring_企业常用方式

    在spring配置文件中配置连接池

    将数据库连接参数放入properties文件

    数据库操作类继承  extends JdbcDaoSupport

    将连接池注入该类即可通过  super.getJdbcTemplate() 获得JDBC模板对象

  步骤1、

<!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"/>

  步骤2、

<!-- 配置連接池對象 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="JdbcUrl" value="${jdbc.JdbcUrl}"></property>
        <property name="DriverClass" value="${jdbc.DriverClass}"></property>
        <property name="User" value="${jdbc.User}"></property>
        <property name="Password" value="${jdbc.Password}"></property>
    </bean>

  

  步骤3、

<!-- 將連接池對象注入DB操作的類中,該類繼承 JdbcDaoSupport-->
    <bean name="JdbcDemo1" class="SpringJDBCDemo.JdbcDemo1">
        <property name="DataSource" ref="dataSource"></property>
    </bean>

 

3、Spring JDBC CRUD测试案例

public class JdbcDemo1 extends JdbcDaoSupport
{
    //新增
    public void add(User u) 
    {
        String sql="insert into uu values(null,?,?)";
        super.getJdbcTemplate().update(sql,u.getUuname(),u.getUupass());
        
    }
    //刪除
    public void delete(int id) {
        
        String sql="delete uu where uuid=?";
        super.getJdbcTemplate().update(sql,id);
    }
    //更新
    public void update(User u) {
        String sql="update uu set uuname=?,uupass=? where uuid=?";
        super.getJdbcTemplate().update(sql,u.getUuname(),u.getUupass(),u.getUuid());
        
    }
    
    //查詢單個對象
    public User Query(int id) {
        
        String sql="select * from uu where uuid=?";
        User user = super.getJdbcTemplate().queryForObject(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u=new User();
                
                u.setUuid(rs.getInt("uuid"));
                u.setUuname(rs.getString("uuname"));
                u.setUupass(rs.getString("uupass"));
                
                //索引是從1開始的
                //System.out.println(rs.getString(2));
                return u;
            }            
            
        }, id);
        
        return user;
    }
    
    //查詢單個值
    public int getTotalCount() {
        String sql="select count(*) from uu";
        return super.getJdbcTemplate().queryForObject(sql,Integer.class);
    }
    
    //查詢多個值
    public List<User> QueryList(){
        String sql="select * from uu";
        return super.getJdbcTemplate().query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
User u=new User();
                
                u.setUuid(rs.getInt("uuid"));
                u.setUuname(rs.getString("uuname"));
                u.setUupass(rs.getString("uupass"));
                return u;
            }
        });
        
    }
    
    //一般方法获取配置spring jdbc 模板
    public JdbcTemplate getTemp() throws Exception 
    {
        //使用C3P0连接池
        ComboPooledDataSource dataSource=new ComboPooledDataSource();
        //配置数据库连接参数
        dataSource.setJdbcUrl("jdbc:oracle:thin:@//localhost:1521/mydb");
        dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
        dataSource.setUser("");
        dataSource.setPassword("");
        //将连接池交给模板
        JdbcTemplate jt=new JdbcTemplate();
        jt.setDataSource(dataSource);
        return jt;
    }
}

二、Spring Xml 配置事务

  导包,引入名称空间

  string tx包

一、事物的传播行为

PROPAGATION_REQUIRED 支持当前事务,如果不存在 就新创建一个(默认)
PROPAGATION_SUPPORTS 支持当前事务,如果不存在 就不使用事务
PROPAGATION_MANDATORY 支持当前事务,如果不存在 就抛出异常
PROPAGATION_REQUIRES_NEW 如果有事务存在,挂起当前事务,创建一个新的事务
PROPAGATION_NOT_SUPPORTED 以非事务的方式运行,如果有事务存在,挂起当前事务
PROPAGATION_NEVER 以非事务的方式运行,如果有事务,抛出异常
PROPAGATION_NESTED 如果当前事务存在,则嵌套事务执行

二、在XML中配置核心事务管理器

<!-- 事务核心管理器 管理器依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

三、配置事务通知

<!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 
                以方法为单位,指定方法应用什么事务属性
          name:方法名称 isolation:隔离级别 propagation:传播行为 read-only:是否只读
--> <tx:method name="save*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" /> <tx:method name="update*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" /> <tx:method name="delete*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" /> <tx:method name="find*" isolation="DEFAULT" read-only="true" propagation="REQUIRED" /> <tx:method name="transfer" isolation="DEFAULT" read-only="false" propagation="REQUIRED" /> </tx:attributes> </tx:advice>

四、将事务通知织入

<!-- 配置织入 -->
    <aop:config>
        <!-- 配置切点表达式 -->
        <aop:pointcut expression="execution(* SpringTranDemo.*.*())" id=" txpc"/>
        <!-- 配置 切面 :通知+切点
            advice-ref:事务通知名称
            pointcut-ref:切点的名称
        -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txpc"/>
    </aop:config>

五、测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class BankTest {

    @Resource(name="BankA")
    private BankA bank;
    
    @Test
    public void transfer() {
        
        bank.addmoney(1, 100);
        int i=1/0;
        bank.submoney(2, 100);
    }
}

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: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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 

<!-- 开启依赖注入扫描注解 -->
<context:component-scan base-package="domain"></context:component-scan>

<!-- 开启AOP 注解完成织入
<aop:aspectj-autoproxy></aop:aspectj-autoproxy> -->

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置連接池對象 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="JdbcUrl" value="${jdbc.JdbcUrl}"></property>
        <property name="DriverClass" value="${jdbc.DriverClass}"></property>
        <property name="User" value="${jdbc.User}"></property>
        <property name="Password" value="${jdbc.Password}"></property>
    </bean>
    <!-- 將連接池對象注入DB操作的類中,該類繼承 JdbcDaoSupport-->
    <bean name="JdbcDemo1" class="SpringJDBCDemo.JdbcDemo1">
        <property name="DataSource" ref="dataSource"></property>
    </bean>
    
    <bean name="BankA" class="SpringTranDemo.BankA">
        <property name="DataSource" ref="dataSource"></property>
    </bean>
    
    <!-- 事务核心管理器 管理器依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 配置事务通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 
                以方法为单位,指定方法应用什么事务属性
                isolation:隔离级别
                propagation:传播行为
                read-only:是否只读
             -->
             <tx:method name="save*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
             <tx:method name="update*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
             <tx:method name="delete*" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
             <tx:method name="find*" isolation="DEFAULT" read-only="true" propagation="REQUIRED" />
             <tx:method name="transfer" isolation="DEFAULT" read-only="false" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice>
    
    <!-- 配置织入 -->
    <aop:config>
        <!-- 配置切点表达式 -->
        <aop:pointcut expression="execution(* SpringTranDemo.*.*())" id=" txpc"/>
        <!-- 配置 切面 :通知+切点
            advice-ref:事务通知名称
            pointcut-ref:切点的名称
        -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txpc"/>
    </aop:config>
</beans>   

 

三、Spring注解配置事务

<?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: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.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 


    <!-- 开启使用注解管理aop事务 -->
    <tx:annotation-driven/>

    <!-- 指定spring读取db.properties配置 -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配置連接池對象 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="JdbcUrl" value="${jdbc.JdbcUrl}"></property>
        <property name="DriverClass" value="${jdbc.DriverClass}"></property>
        <property name="User" value="${jdbc.User}"></property>
        <property name="Password" value="${jdbc.Password}"></property>
    </bean>
    
    
    <bean name="BankA" class="SpringTranDemo1.BankA">
        <property name="DataSource" ref="dataSource"></property>
    </bean>
    
    <!-- 事务核心管理器 管理器依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
        
</beans>   
public class BankA extends JdbcDaoSupport {

    
    public void addmoney(int id,double money) {
        
        String sql="update t_ubank set money=money+? where t_id=?";
        super.getJdbcTemplate().update(sql,money,id);
    }
    
    public void submoney(int id,double money) {
        String sql="update t_ubank set money=money-? where t_id=?";
        super.getJdbcTemplate().update(sql,money,id);
    }
    
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false)
    public void tranfer() {
        
        addmoney(1, 1000);
        int i=1/0;
        submoney(2, 100);
    }
}

重点: 

 <!-- 开启使用注解管理aop事务 -->
    <tx:annotation-driven/>
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,readOnly = false)
    public void tranfer() {
        
        addmoney(1, 1000);
        int i=1/0;
        submoney(2, 100);
    }

说明:

  @Transactional不仅可以加在方法上,也可以加在类上,如果类中的方法想要换一套配置

    可以再在方法上进行注解生命用以覆盖类上的配置

posted on 2020-08-12 16:14  harrietszhang  阅读(166)  评论(0编辑  收藏  举报