学习笔记_Spring_day04

数据库操作模板JdbcTemplate和事务控制

数据库操作模板JdbcTemplate

JdbcTemplate概述
JdbcTemplate是Spring框架中提供的一个对象,对原始的JDBC API进行简单封装,其用法与DBUtils类似.
JdbcTemplate对象的创建
使用Spring内置的数据源DriverManagerDataSource,需要在bean.xml中配置如下:

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

        <!--配置DataSource-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/day17"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>

JdbcTemplate的增删改查操作

实现增删改
JdbcTemplateDemo类:

public static void main(String[] args) {
        //1.获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取对象
        JdbcTemplate jt =ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行操作
        //保存操作
        //jt.update("insert into account(name,money)values(?,?)","名字",5000);
        //更新操作
        //jt.update("update account set money = money-? where id = ?",300,6);
        //删除操作
        //jt.update("delete from account where id = ?",6);
        }}

查询

 //1.查询所有
 List<Account> accounts = jt.query("select * from account where money > ?",
            new BeanPropertyRowMapper<Account>(Account.class),1000f);
     for (Account account : accounts) {
         System.out.println(account);
     }
     //2.查询一个
     List<Account> accounts = jt.query("select * from account where id = ?",
             new BeanPropertyRowMapper<Account>(Account.class),1);
     System.out.println(accounts.isEmpty()?"无内容":accounts.get(0));
     //3.聚合查询
      Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
     System.out.println(count);

在DAO使用JdbcTemplate

1.第一种方式
在DAO中定义jdbctemplate
注入jdbctemplate

  <!--配置账户的持久层-->
        <bean id="accountDao" class="com.itheima.dao.impl.IAccountDaoImpl">
          <property name="jdbcTemplate" ref="jdbcTemplate"></property>
        </bean>
<!--配置jdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

实现类

//账户的持久层实现类
public class AccountDaoImpl implements IAccountDao {
    private JdbcTemplate jdbcTemplate;	// JdbcTemplate对象

    // JdbcTemplate对象的set方法
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    // DAO层方法
    @Override
    public Account findAccountById(Integer id) {
        // 实现...
    }
    // 其它DAO层方法...
}

第二种方式
DAO层对象继承JdbcDaoSupport
在实际项目中,我们会创建许多DAO对象,若每个DAO对象都注入一个JdbcTemplate对象,会造成代码冗余.实际的项目中我们可以让DAO对象继承Spring内置的JdbcDaoSupport类.在JdbcDaoSupport类中定义了JdbcTemplate和DataSource成员属性,在实际编程中,只需要向其注入DataSource成员即可,DataSource的set方法中会注入JdbcTemplate对象.

bean.xml

<!--配置账户的持久层-->
     <bean id="accountDao" class="com.itheima.dao.impl.IAccountDaoImpl">
          <property name="dataSource" ref="dataSource"></property>
      </bean>

实现类

//账户的持久层实现类
public class IAccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts=getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }
    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts=getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<>(Account.class),accountName);
        if (accounts.isEmpty()){
            return null;
        }
        if ((accounts.size()>1)){
            throw new RuntimeException("多了");
        }
        return accounts.get(0);
    }
    @Override
    public void updateAccount(Account account) {
        getJdbcTemplate().update("update account set name= ?,money=? where id = ?",account.getName(),account.getMoney(),account.getId());
    }
}

区别:第一种使用所有配置方式,第二种只能使用xml。

事务控制(TransactionManager)

Spring事务控制

1,JavaEE 体系进行分层开发,事务处理位于业务层,Spring提供了分层设计业务层的事务处理解决方案

2.Spring 框架为我们提供了一组事务控制的接口,这组接口在spring-tx-5.0.2.RELEASE.jar中
3.Spring 的事务控制都是基于AOP的,它既可以使用配置的方式实现,也可以使用编程的方式实现.推荐使用配置方式实现.

Spring中事务控制的API

PlatformTransactionManager接口是Spring提供的事务管理器,它提供了操作事务的方法如下:

  1. TransactionStatus getTransaction(TransactionDefinition definition): 获得事务状态信息
    void commit(TransactionStatus status): 提交事务
    void rollback(TransactionStatus status): 回滚事务
    在实际开发中我们使用其实现类。
    真正管理事务的对象:class =“org.springframework.jdbc.datasource.DataSourceTransactionManager“
    使用SpringJDBC或iBatis进行持久化数据时使用

  2. TransactionDefinition: 事务定义信息对象,提供查询事务定义的方法如下:
    String getName(): 获取事务对象名称
    int getIsolationLevel(): 获取事务隔离级别,设置两个事务之间的数据可见性

  3. getPropagationBehavior(): 获取事务传播行为,设置新事务是否事务以及是否使用当前事务.
    我们通常使用的是前两种: REQUIRED和SUPPORTS.事务传播行为如下:

    REQUIRED: Spring默认事务传播行为. 若当前没有事务,就新建一个事务;若当前已经存在一个事务中,加入到这个事务中.增删改查操作均可用
    SUPPORTS: 若当前没有事务,就不使用事务;若当前已经存在一个事务中,加入到这个事务中.查询操作可用

    int getTimeout(): 获取事务超时时间. Spring默认设置事务的超时时间为-1,表示永不超时.
    boolean isReadOnly(): 获取事务是否只读. Spring默认设置为false,建议查询操作中设置为true

  4. TransactionStatus: 事务状态信息对象,提供操作事务状态的方法如下:
    void flush(): 刷新事务
    boolean hasSavepoint(): 查询是否存在存储点
    boolean isCompleted(): 查询事务是否完成
    boolean isNewTransaction(): 查询是否是新事务
    boolean isRollbackOnly(): 查询事务是否回滚
    void setRollbackOnly(): 设置事务回滚

使用Spring进行事务控制

基于xml的声明式事务控制(重点)

1.导入jar包

2.创建bean.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: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/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>

3.准备数据库和实体类

4.业务层接口和实现类

//账户业务层接口
public interface IAccountService {
    //根据id查询
    Account findAccountById(Integer accountId);
    //转账
    void transfer(String sourceName, String targetName, Float money);
}
/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);

    }
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        System.out.println("transfer....");
            //2.1根据名称查询转出账户
            Account source = accountDao.findAccountByName(sourceName);
            //2.2根据名称查询转入账户
            Account target = accountDao.findAccountByName(targetName);
            //2.3转出账户减钱
            source.setMoney(source.getMoney()-money);
            //2.4转入账户加钱
            target.setMoney(target.getMoney()+money);
            //2.5更新转出账户
            accountDao.updateAccount(source);
//            int i=1/0;
            //2.6更新转入账户
            accountDao.updateAccount(target);
    }
}

5.dao接口和实现类

/**
 * 账户的持久层接口
 */
public interface IAccountDao {

    /**
     * 根据Id查询账户
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 根据名称查询账户
     * @param accountName
     * @return
     */
    Account findAccountByName(String accountName);

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
}
/**
 * 账户的持久层实现类
 */
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {

    @Override
    public Account findAccountById(Integer accountId) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return accounts.isEmpty()?null:accounts.get(0);
    }

    @Override
    public Account findAccountByName(String accountName) {
        List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(accounts.isEmpty()){
            return null;
        }
        if(accounts.size()>1){
            throw new RuntimeException("结果集不唯一");
        }
        return accounts.get(0);
    }

    @Override
    public void updateAccount(Account account) {
        super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
    }
}

6.在配置文件中配置业务层和持久层

 <!--配置业务层-->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>

    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/day17"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

7.配置步骤
spring中基于xml的声明式事务通知配置:

  1. 配置事务管理器
  2. 配置事务通知
    此时我们要导入事务约束,使用tx:advice标签配置事务通知
    属性:
    id:给事务通知起一个唯一标识
    transaction-manager:给事务通知提供一个事务管理器引用
  3. 配置AOP中的通用切入点表达式
  4. 建立事务通知和切入点表达式的对应关系
  5. 配置事务的属性
    是在事务的通知tx:advice标签的内部
<!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<注入datasource>
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务的通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <!-- 配置事务的属性
        isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
        propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
        read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
        timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
        rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
        no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
        -->
        <tx:attributes>
           <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
        </tx:attributes>
    </tx:advice>

    <!--配置aop-->
    <aop:config>
        <!--切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"/>
        <!--建立切入点表达式和事物通知的关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

使用半注解配置事务控制

/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
@Service("accountService")
@Transactional(propagation= Propagation.SUPPORTS,readOnly=true)//只读型事务的配置
public class AccountServiceImpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    //需要的是读写型事务配置
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false)
    @Override
    public void transfer(String sourceName, String targetName, Float money) {
        // 转账操作的实现...
    }
}

    <!-- 配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>
  <!-- spring中基于注解 的声明式事务控制配置步骤
        1、配置事务管理器
        2、开启spring对注解事务的支持
        3、在需要事务支持的地方使用@Transactional注解
     -->
    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 开启spring对注解事务的支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

该注解可以加在接口,类或方法上
对接口加上@Transactional注解,表示对该接口的所有实现类进行事务控制
对类加上@Transactional注解,表示对类中的所有方法进行事务控制
对具体某一方法加以@Transactional注解,表示对具体方法进行事务控制
三个位置上的注解优先级依次升高

使用纯注解式事务配置

不使用xml配置事务,就要在cn.maoritian.config包下新建一个事务管理配置类TransactionConfig,对其加上@EnableTransactionManagement注解以开启事务控制.
事务控制配置类TransactionConfig类的源码如下:

@Configuration                  
@EnableTransactionManagement    // 开启事务控制
public class TransactionConfig {
    // 创建事务管理器对象
    @Bean(name="transactionManager")
    public PlatformTransactionManager createTransactionManager(@Autowired DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

JDBC配置类JdbcConfig类的源码如下:

@Configuration                                  
@PropertySource("classpath:jdbcConfig.properties")  
public class JdbcConfig {

    @Value("${jdbc.driver}")    
    private String driver;

    @Value("${jdbc.url}")   
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")  
    private String password;

    // 创建JdbcTemplate对象
    @Bean(name="jdbcTemplate")
    @Scope("prototype") 
    public JdbcTemplate createJdbcTemplate(@Autowired DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }
    
    // 创建数据源对象
    @Bean(name="dataSource")
    public DataSource createDataSource(){
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        return ds;
    }
}

Spring主配置类SpringConfig源代码如下:

@Configuration
@ComponentScan("cn.maoritian")
@Import({JdbcConfig.class, TransactionConfig.class})
public class SpringConfig {
}

发布了33 篇原创文章 · 获赞 0 · 访问量 497

猜你喜欢

转载自blog.csdn.net/naerjiajia207/article/details/103482424