JavaEE学习日志(九十一)

  • Spring
  • AOP管理转账事务
  • xml配置实现
  • 注解配置实现
  • jdbcTemplate
  • 三种数据源的配置
  • jdbcTemplate的查询操作
  • jdbcTemplate的增删改操作
  • jdbcTemplate在dao层中两种使用方法


Spring

AOP管理转账事务

xml配置实现

AccountDaoImpl

package com.itheima.dao.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.utils.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;

@Repository
public class AccountDaoImpl implements AccountDao {
    @Autowired
    QueryRunner queryRunner;
    @Autowired
    ConnectionUtil connectionUtil;
    @Override
    public Account findByName(String name) {
        String sql = "select * from account where name = ?";
        try {
            return queryRunner.query(connectionUtil.getThreadConnection(),sql,new BeanHandler<Account>(Account.class),name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void update(Account account) {
        String sql = "update account set money = ? where name = ?";
        try {
            queryRunner.update(connectionUtil.getThreadConnection(),sql,account.getMoney(),account.getName());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

AccountServiceImpl

package com.itheima.service.impl;

import com.itheima.dao.AccountDao;
import com.itheima.domain.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountDao accountDao;
    @Override
    public void transfer(String fromName, String toName, Float money) {
        //查询转账的账户
        Account fromAccount = accountDao.findByName(fromName);
        //查询接收的账户
        Account toAccount = accountDao.findByName(toName);
        //开始转账
        fromAccount.setMoney(fromAccount.getMoney()-money);
        toAccount.setMoney(toAccount.getMoney()+money);
        //持久化到数据库
        accountDao.update(fromAccount);
        accountDao.update(toAccount);
    }
}

TransactionManager作为通知对象

package com.itheima.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事务管理器:是通知对象
 * @author 黑马程序员
 * @Company http://www.ithiema.com *
 * @Version 1.0
 */
@Component
public class TransactionManager {

    @Autowired
    private ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    //开启事务
    public void beginTransaction() {
        //从当前线程上获取连接,实现开启事务
        try {
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交事务
    public void commit() {
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //回滚事务
    public void rollback() {
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //释放连接
    public void release() {
        try {
            connectionUtil.getThreadConnection().setAutoCommit(true);
            //关闭连接(还回池中)
            connectionUtil.getThreadConnection().close();
            //解绑线程:把连接和线程解绑
            connectionUtil.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

ConnectionUtil用于获取连接

package com.itheima.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 一个管理连接的工具类,用于实现连接和线程的绑定
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Component
public class ConnectionUtil {
    private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
    @Autowired
    private DataSource dataSource;
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    /**
     * 获取当前线程上绑定的连接
     * @return
     */
    public Connection getThreadConnection() {
        try {
            //1.先看看线程上是否绑了
            Connection conn = tl.get();
            if(conn == null) {
                //2.从数据源中获取一个连接
                conn = dataSource.getConnection();
                //3.和线程局部变量绑定
                tl.set(conn);
            }
            //4.返回线程上的连接
            return tl.get();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 把连接和当前线程解绑
     */
    public void remove() {
        tl.remove();
    }
}

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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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">
    <!--开启注解-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

    <!--dao层需要注入qr-->
    <bean id = "queryRunner" class="org.apache.commons.dbutils.QueryRunner"></bean>
    <!--创建dataSource-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--引入外部属性文件-->
    <context:property-placeholder location="jdbc.properties"></context:property-placeholder>

    <!--使用aop解决事务问题
        事务管理器类:通知对象
    -->
    <aop:config>
        <!--切面-->
        <aop:aspect ref="transactionManager">
            <!--配置切入点-->
            <aop:pointcut id="pointcut" expression="execution(* com.itheima.service..*.*(..))"/>
            <!--配置通知-->
            <!--前置增强,开启事务-->
            <aop:before method="beginTransaction" pointcut-ref="pointcut"></aop:before>
            <!--后置增强,提交事务-->
            <aop:after-returning method="commit" pointcut-ref="pointcut"></aop:after-returning>
            <!--异常增强,回滚事务-->
            <aop:after-throwing method="rollback" pointcut-ref="pointcut"></aop:after-throwing>
            <!--最终增强,释放资源-->
            <aop:after method="release" pointcut-ref="pointcut"></aop:after>

        </aop:aspect>
    </aop:config>




</beans>

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestSpring {
    @Autowired
    AccountService accountService;
    @Test
    public void test(){
        accountService.transfer("aaa","ccc",20F);
    }
}

注解配置实现

xml中

<!--开启自动代理注解-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

在通知对象中配置注解

package com.itheima.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;

/**
 * 事务管理器:是通知对象
 * @author 黑马程序员
 * @Company http://www.ithiema.com *
 * @Version 1.0
 */
@Component
@Aspect
public class TransactionManager {

    @Autowired
    private ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    @Pointcut("execution(* com.itheima.service..*.*(..))")
    public void pointcut(){}
    /**
     * 环绕增强
     */
    @Around("pointcut()")
    public void around(ProceedingJoinPoint joinPoint){
        //执行原方法
        try {
            //前置增强
            beginTransaction();
            joinPoint.proceed();
            //后置增强
            commit();
        } catch (Throwable throwable) {
            //异常增强
            rollback();
            throwable.printStackTrace();
        } finally {
            //最终增强
            release();
        }
    }

    //开启事务
    public void beginTransaction() {
        //从当前线程上获取连接,实现开启事务
        try {
            connectionUtil.getThreadConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交事务
    public void commit() {
        try {
            connectionUtil.getThreadConnection().commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    //回滚事务
    public void rollback() {
        try {
            connectionUtil.getThreadConnection().rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //释放连接
    public void release() {
        try {
            connectionUtil.getThreadConnection().setAutoCommit(true);
            //关闭连接(还回池中)
            connectionUtil.getThreadConnection().close();
            //解绑线程:把连接和线程解绑
            connectionUtil.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

也可以不配置切入点,直接在通知的注解中写上表达式

@Around("execution(* com.itheima.service..*.*(..))")

jdbcTemplate

三种数据源的配置

三种数据源:c3p0,dbcp,spring自带的数据源

引入依赖:其中spring自带的数据源里包含了jdbcTemplate

<dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--dbcp数据源-->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!--spring自带数据源-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

配置三种数据源

<!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--配置c3p0数据源-->
    <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--配置dbcp-->
    <bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
    <!--spring自带的数据源-->
    <bean id="springDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

jdbcTemplate的查询操作

一、查询全部

  • queryForList(sql语句) 返回值是list集合,list集合中是map集合
  • query(sql语句,列与属性的映射) 返回的是list集合,集合中是查询的对象

创建列与属性的映射类:结果集对象,每次都包含一行数据

package com.itheima.mapper;

import com.itheima.domain.Account;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;

public class AccountRowMapper implements RowMapper<Account> {
    /**
     *
     * @param resultSet 结果集对象,只包含了一行数据
     * @param i
     * @return
     * @throws SQLException
     */
    @Override
    public Account mapRow(ResultSet resultSet, int i) throws SQLException {
        Account account = new Account();
        int id = resultSet.getInt("id");
        account.setId(id);
        account.setName(resultSet.getString("name"));
        account.setMoney(resultSet.getFloat("money"));
        return account;
    }
}
@Test
    public void findAll(){
        String sql = "select * from account";
        //queryForList方法返回值是list集合,list集合中是map集合
//        List<Map<String, Object>> accountList = jdbcTemplate.queryForList(sql);
//        for (Map<String, Object> map : accountList) {
//            System.out.println(map);
//        }

        //query
        List<Account> list = jdbcTemplate.query(sql, new AccountRowMapper());
        for (Account account : list) {
            System.out.println(account);
        }

    }

二、根据id查询

  • query(sql语句,列与属性的映射,参数) 和上述基本一致,返回一个list集合
  • queryForObject(sql语句,列与属性的映射,参数) 查询一个对象
  • queryForObject(sql语句,参数列表(必须是数组类型),jdbcTemplate自带映射:必须保证属性和列名一致) 这个方法只能当列与属性名相同时使用,也是返回一个对象,不建议使用
@Test
    public void findById(){
        String sql = "select * from account where id = ?";
//        List<Account> list = jdbcTemplate.query(sql, new AccountRowMapper(),1);

        //queryForObject(sql语句,列与属性的映射,参数)查询一个对象
//        Account account = jdbcTemplate.queryForObject(sql, new AccountRowMapper(), 1);
//        System.out.println(account);
        //queryForObject(sql语句,参数列表(必须是数组类型),jdbcTemplate自带映射:必须保证属性和列名一致)
        Account account = jdbcTemplate.queryForObject(sql, new Object[]{1}, new BeanPropertyRowMapper<>(Account.class));
        System.out.println(account);

    }

三、聚合函数

  • queryForObject(sql, 返回值类型)
@Test
    public void totalCount() {
        String sql = "select count(*) from account";
        //queryForObject(sql语句,返回值类型)
        Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(integer);
    }

jdbcTemplate的增删改操作

和dbUtils一样,update方法

@Test
    public void save(){
        String sql = "insert into account values(null,?,?)";
        jdbcTemplate.update(sql,"ddd",500);

    }

    @Test
    public void update(){
        String sql = "update account set money = ? , name = ? where id = ?";
        jdbcTemplate.update(sql,1000F,"eee",5);
    }

    @Test
    public void del() {
        String sql = "delete from account where id = ?";
        jdbcTemplate.update(sql,5);
    }

jdbcTemplate在dao层中两种使用方法

第一种:和上述一样,使用spring相关技术即可

第二种:

  1. 在dao层的实现类种继承接口JdbcDaoSupport
public class AccountDaoImpl2 extends JdbcDaoSupport implements AccountDao
  1. 所有的dao对象需要在xml中创建,并通过set方法注入数据源对象
<!--创建dao层对象-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl2">
        <!--通过set方法注入数据源-->
        <property name="dataSource" ref="springDataSource"></property>
    </bean>
  1. 使用getJdbcTemplate() 获取jdbcTemplate
@Override
    public List<Account> findAll() {
        String sql = "select * from account";
        List<Account> accountList = getJdbcTemplate().query(sql, new AccountRowMapper());
        return accountList;
    }