spring学习笔记(8):Spring中的template和事务控制

文章目录

  • 一、工程准备
    • 1.数据库
    • 2.pom.xml
    • 2.实体类
    • 3.JdbcTemplate的最基本的使用
      • 3.1代码
  • 二、JdbcTemplate
    • 1.基于IOC配置的JdbcTemplate使用
      • 1.1bean.xml
    • 1.2测试类
    • 2.实现单表的CRUD
    • 3.实现DAO层
      • 3.1接口
      • 3.2实现类
      • 3.3bean.xml
      • 3.4测试类
    • 4.JdbcDaoSupport
  • 三、Spring的事务控制案例的环境搭建
    • 1实体类
    • 2Dao层
      • 2.1接口
      • 2.2实现类
    • 3业务层
      • 3.1接口
      • 3.2实现类
    • 4bean.xml
    • 5测试类
      • 5.1暂无事务控制,测试类结果
  • 四、基于xml的声明式事务控制
    • 1.配置步骤
    • 2.测试效果
  • 五、基于注解的声明式事务控制配置
    • 1bean.xml
    • 2Dao层![在这里插入图片描述](https://img-blog.csdnimg.cn/20191015154957334.png)
    • 3.业务层(注解事务配置)
    • 4.效果
    • 5.基于注解和基于xml的事务控制配置对比
  • 六基于纯注解的声明式事务控制的配置
    • 1.和数据库连接相关的配置类
    • 2.和事务相关的配置类
    • 3.主配置类
    • 4.测试类改造
    • 5.效果
  • 七、Spring5的新特性

一、工程准备

1.数据库

沿用前文的account
spring学习笔记(8):Spring中的template和事务控制_第1张图片

2.pom.xml

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>

        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-txartifactId>
            <version>5.0.2.RELEASEversion>
        dependency>

        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.6version>
        dependency>
    dependencies>

2.实体类


public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }

}

3.JdbcTemplate的最基本的使用

3.1代码

public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //1.准备数据源 spring的内置数据源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/eesy");
        ds.setUsername("root");
        ds.setPassword("admin");
        //2.创建template对象
        JdbcTemplate jt = new JdbcTemplate();
        //3.给它设置数据源
        jt.setDataSource(ds);
        //4.执行操作
        jt.execute("insert  into account(name,money) values ('csacas',1000)");
    }
}

二、JdbcTemplate

1.基于IOC配置的JdbcTemplate使用

1.1bean.xml

    <!--配置JdbcTemplate-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <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/eesy"></property>
        <property name="username" value="root"></property>
        <property name="password" value="admin"></property>
    </bean>

1.2测试类

public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //1.获取IOC对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取jdbcTemplate对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3.执行方法
        jt.execute("insert  into account(name,money) values ('jdbcTemplate_IOC',1000)");

    }
}

2.实现单表的CRUD

public class JdbcTemplateDemo3 {
    public static void main(String[] args) {
        //1.获取IOC对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取jdbcTemplate对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);


        //3.保存
        jt.update("insert  into account(name,money) values ('jdbcTemplate_IOC',1000)");
        //4.更新
        jt.update("update account set name = ?, money = ? where id=?", "test",4444,6);
        //5.删除
        jt.update("delete from account where id=?",8);
        //6.查询所有
        List<Account> accounts = jt.query("select * from account where money > ?", new BeanPropertyRowMapper<Account>(Account.class),1000f);
        for (Account account : accounts) {
            System.out.println(account);
        }
        //7.查询一个
        List<Account> account_1 = jt.query("select * from account where id= ?", new BeanPropertyRowMapper<Account>(Account.class),1000f);
        System.out.println(account_1.isEmpty() ? "没有内容" : account_1.get(0));
        //8.查询返回一行一列
        Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
        System.out.println(count);
        
    }
}
  • 注意
    spring学习笔记(8):Spring中的template和事务控制_第2张图片

3.实现DAO层

3.1接口

public interface IAccountDao {

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

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

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
}

3.2实现类

public class AccountDaoImpl implements IAccountDao {

    private JdbcTemplate jdbcTemplate;
    //等待注入
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

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

    public Account findAccountByName(String accountName) {
        List<Account> accounts = jdbcTemplate.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);
    }

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

}

3.3bean.xml


    <bean id="accountDao" class="com.xpt.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate">property>
    bean>

3.4测试类

public class JdbcTemplateDemo4 {
    public static void main(String[] args) {
        //1.获取IOC对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.获取dao对象
        IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class);
        //3.调用方法
        Account accountById = accountDao.findAccountById(1);
        System.out.println(accountById);
    }
}

4.JdbcDaoSupport

spring学习笔记(8):Spring中的template和事务控制_第3张图片
spring学习笔记(8):Spring中的template和事务控制_第4张图片

三、Spring的事务控制案例的环境搭建

  • 基于前文JdbcTemplate进行搭建

1实体类

public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

2Dao层

2.1接口

public interface IAccountDao {

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

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

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
}

2.2实现类

public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {


    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);
    }


    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);
    }


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

3业务层

3.1接口

/**
 * 账户的业务层接口
 */
public interface IAccountService {
    /**
     * 根据id查询账户信息
     * @param accountId
     * @return
     */
    Account findAccountById(Integer accountId);

    /**
     * 转账
     * @param sourceName    转成账户名称
     * @param targetName    转入账户名称
     * @param money         转账金额
     */
    void transfer(String sourceName, String targetName, Float money);
}

3.2实现类

public class AccountServiceImpl implements IAccountService{

    private IAccountDao accountDao;

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


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

    }
    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);
    }
}

4bean.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    
    <bean id="accountService" class="com.xpt.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao">property>
    bean>

    
    <bean id="accountDao" class="com.xpt.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/eesy">property>
        <property name="username" value="root">property>
        <property name="password" value="admin">property>
    bean>
beans>

5测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);

    }

}

5.1暂无事务控制,测试类结果

spring学习笔记(8):Spring中的template和事务控制_第5张图片

四、基于xml的声明式事务控制

1.配置步骤

  • 配置步骤一般如下
    spring学习笔记(8):Spring中的template和事务控制_第6张图片- 具体过程
    spring学习笔记(8):Spring中的template和事务控制_第7张图片

2.测试效果

spring学习笔记(8):Spring中的template和事务控制_第8张图片

五、基于注解的声明式事务控制配置

1bean.xml

  • 首先需要约束的支持
    spring学习笔记(8):Spring中的template和事务控制_第9张图片
  • 然后进行配置
    spring学习笔记(8):Spring中的template和事务控制_第10张图片

2Dao层spring学习笔记(8):Spring中的template和事务控制_第11张图片

3.业务层(注解事务配置)

spring学习笔记(8):Spring中的template和事务控制_第12张图片

4.效果

spring学习笔记(8):Spring中的template和事务控制_第13张图片

5.基于注解和基于xml的事务控制配置对比

spring学习笔记(8):Spring中的template和事务控制_第14张图片

六基于纯注解的声明式事务控制的配置

主要回顾一下如何进行纯注解的配置

1.和数据库连接相关的配置类


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;
    
    
    
    @Bean(name = "jdbcTemplate")
    public JdbcTemplate createJdbcTemplate(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;
    }
}

2.和事务相关的配置类

public class TransactionConfig {

    /**
     * 用于创建事务管理器对象
     * @param dataSource
     * @return
     */
    @Bean(name = "transactionManager")
    public PlatformTransactionManager createPlatformTransactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}

3.主配置类

@Configuration
@ComponentScan("com.xpt")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")
@EnableTransactionManagement//
public class SpringConfiguration {
    

}

4.测试类改造

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {

    @Autowired
    private IAccountService as;

    @Test
    public  void testTransfer(){
        as.transfer("aaa","bbb",100f);

    }

}

5.效果

spring学习笔记(8):Spring中的template和事务控制_第15张图片

七、Spring5的新特性

你可能感兴趣的:(spring,JavaWeb)