Spring整合JDBC和Spring中AOP事务(三)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hao_DaYu/article/details/79974623

一. Spring整合JDBC
1)spring提供了很多模板整合dao技术

ORM持久化技术 模板类
JDBC org.springframework.jdbc.core.JdbcTemplate
Hibernate5.0 org.springframework.orm.hibernate5.HibernateTemplate
IBatis(MyBatis) org.springframework.orm.ibatis.SqlMapClientTemplate
JPA org.springfrmaework.orm.jpa.JpaTemplate

2)spring中提供了一个可以操作数据库的对象,对象封装了jdbc技术
JdbcTemplate模板对象与DButils中的QueryRunner非常相似
例子:

    @Test
    public void fun2() throws PropertyVetoException{
        //准备连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/spring_day03");
        dataSource.setUser("root");
        dataSource.setPassword("123456");

        //创建模板对象
        JdbcTemplate jt = new JdbcTemplate(dataSource);

        String sql = "insert into t_user values(null,'rose')";
        jt.update(sql);
    }

3)Spring操作数据库步骤
1.导包
2.准备数据库
3.书写dao

UserDaoImpl.class

package com.hao.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.hao.bean.User;
import com.hao.dao.UserDao;

public class UserDaoImpl implements UserDao {

    private JdbcTemplate jt;

    @Override
    public void save(User user) {
        String sql = "insert into t_user values(null,?)";
        jt.update(sql, user.getName());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from t_user where id = ?";
        jt.update(sql, id);
    }

    @Override
    public void update(User user) {
        String sql = "update t_user set name = ? where id = ?";
        jt.update(sql, user.getName(), user.getId());
    }

    @Override
    public List<User> find() {
        String sql = "select * from t_user";
        return jt.query(sql, new RowMapper<User>() {

            @Override
            public User mapRow(ResultSet rs, int arg1) throws SQLException {
                User u = new User();
                u.setId(rs.getInt("id"));
                u.setName(rs.getString("name"));
                return u;
            }

        });
    }

    public void setJt(JdbcTemplate jt) {
        this.jt = jt;
    }

}

4.配置Spring xml
applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">


    <!-- 将连接池配置到容器中 -->

    <bean name="dataSource" class=" com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring_day03"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!-- 配置JDBCTemplate -->
    <bean name="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 将userDao放到容器中 -->
    <bean name="userDao" class="com.hao.dao.impl.UserDaoImpl">
        <property name="jt" ref="jdbcTemplate"></property>
    </bean>
</beans>

5.测试

    @Test
    public void fun3(){
         ApplicationContext ac = new ClassPathXmlApplicationContext(
                    "applicationContext.xml");
            UserDao ud = (UserDao)ac.getBean("userDao");

            User user = new User();
            user.setName("tom");
            ud.save(user);
//          ud.delete(1);
    }

6.使用外部的Properties文件来读取jdbc配置
db.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring_day03
jdbc.user=root
jdbc.password=123456

applicationContext.xml

    <!-- 指定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>

二.Spring中AOP的事务
1)Spring中封装了事务管理代码
1,事务操作
打开事务
提交事务
回滚事务
2,操作事务对象
因为在不同平台,操作事务的代码各不相同,Spring提供了一个接口

2)Spring管理事务的方式

1,编码式

AccounServiceImpl.class(接口自己编写)

package com.hao.service.impl;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.hao.dao.AccountDao;
import com.hao.service.AccountService;

public class AccountServiceImpl implements AccountService {

    private AccountDao dao;
    private TransactionTemplate tt;

    @Override
    public void transfer(final Integer from, final Integer id,
            final Double money) {
        // TODO Auto-generated method stub

        tt.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                dao.decreaseMoney(id, money);
                dao.increaseMoney(from, money);
            }
        });
    }

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }

}

AccountDaoImpl.class

package com.hao.dao.impl;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.hao.dao.AccountDao;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void increaseMoney(Integer id, Double money) {
        String sql = "update t_money set money=money+? where id = ?";
        getJdbcTemplate().update(sql, money, id);
    }

    @Override
    public void decreaseMoney(Integer id, Double money) {
        String sql = "update t_money set money=money-? where id = ?";
        getJdbcTemplate().update(sql, money, id);
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">


    <!-- 指定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>
    <!-- 1,将核心事务管理器配置到Spring容器中 -->
    <!-- 事务核心管理器,封装了所有的事务操作,依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 2,配置TransactionTemplate模板对象 -->
    <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!-- 3.将事务模板注入service -->
    <bean name="accountDao" class="com.hao.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean name="accountService" class="com.hao.service.impl.AccountServiceImpl">
        <property name="dao" ref="accountDao"></property>
        <property name="tt" ref="transactionTemplate"></property>
    </bean> 
</beans>

测试

@Test
    public void fun4(){
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        AccountService as = (AccountService)ac.getBean("accountService");

        as.transfer(2, 1, 200d);
    }

2,xml配置(aop)
Dao类不变
AccountServiceImpl.class

package com.hao.service.impl;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.hao.dao.AccountDao;
import com.hao.service.AccountService;

public class AccountServiceImpl implements AccountService {

    private AccountDao dao;
    @Override
    public void transfer(Integer from, Integer id, Double money) {
        dao.decreaseMoney(id, money);
        int i = 1/0;
        dao.increaseMoney(from, money);
    }

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }

}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">


    <!-- 指定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>
    <!-- 1,将核心事务管理器配置到Spring容器中 -->
    <!-- 事务核心管理器,封装了所有的事务操作,依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 2,配置TransactionTemplate模板对象 -->
    <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!-- 3.将事务模板注入service -->
    <bean name="accountDao" class="com.hao.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean name="accountService" class="com.hao.service.impl.AccountServiceImpl">
        <property name="dao" ref="accountDao"></property>
        <property name="tt" ref="transactionTemplate"></property>
    </bean> 


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

    <!-- 配置将通知织入目标对象 -->
    <aop:config>
        <!-- 配置切点表达式 -->                      
        <aop:pointcut expression="execution(* com.hao.service.impl.*ServiceImpl.*(..))" id="txPc"/>
        <!-- 
        配置切面:通知+切点
        advice-ref:通知的名称
        pointcut-ref:切点的名称
         -->
         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPc"/>
    </aop:config>

</beans>

测试

    //xml配置AOP
    @Test
    public void fun5(){
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        AccountService as = (AccountService)ac.getBean("accountService");

        as.transfer(2, 1, 200d);
    }

3,注解配置(aop)

Dao类不变
AccountServiceImpl.class

package com.hao.service.impl;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.hao.dao.AccountDao;
import com.hao.service.AccountService;
//注解形式配置
@Transactional(isolation=Isolation.DEFAULT,propagation=Propagation.REQUIRED,readOnly=false)
public class AccountServiceImpl implements AccountService {

    private AccountDao dao;
    @Override
    public void transfer(Integer from, Integer id, Double money) {
        dao.decreaseMoney(id, money);
        dao.increaseMoney(from, money);
    }

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    public void setTt(TransactionTemplate tt) {
        this.tt = tt;
    }
}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">


    <!-- 指定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>
    <!-- 1,将核心事务管理器配置到Spring容器中 -->
    <!-- 事务核心管理器,封装了所有的事务操作,依赖于连接池 -->
    <bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 2,配置TransactionTemplate模板对象 -->
    <bean name="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>

    <!-- 3.将事务模板注入service -->
    <bean name="accountDao" class="com.hao.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <bean name="accountService" class="com.hao.service.impl.AccountServiceImpl">
        <property name="dao" ref="accountDao"></property>
        <property name="tt" ref="transactionTemplate"></property>
    </bean> 


    <!-- 注解配置aop事务 -->
    <tx:annotation-driven/>
</beans>

测试

//注解配置aop事务
    @Test
    public void fun6(){
        ApplicationContext ac = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        AccountService as = (AccountService)ac.getBean("accountService");

        as.transfer(2, 1, 200d);
    }
阅读更多

没有更多推荐了,返回首页