Spring-JdbcTemplate&&Transaction

Spring-JdbcTemplate

pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

bean.xlm

jdbcTemplate:添加容器

DriverManagerDataSource:spring内置数据源

	    //配置jdbcTemplate
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="ds"/>
    </bean>
    //spring内置数据源
    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306spring?useSSL=false"/>
        <property name="username" value="****"/>
        <property name="password" value="****"/>
    </bean>

连接成功测试

package com.cat.jdbctemplate;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * @author cat
 * @name [ssmDemo] com.cat.jdbctemplate /JdbcTemplateDemo01
 * @create 2021-01-12 10:09
 * jdbctemplate连通测试
 */
public class JdbcTemplateDemo02 {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jt = context.getBean("jdbcTemplate", JdbcTemplate.class);
        jt.execute("insert into account(name,MONEY)values('eee',1000)");
    }
}

CRUD,查询可以都使用query()方法

public class JdbcTemplateDemo03 {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");

        //执行操作
        //1.保存
//        jt.update("insert into account(name, money) values (?,?)","kitt",456f);
        //2.更新
//        jt.update("update account set NAME=?,money=? where id=?","王五",7777f,5);
        //3.删除
//        jt.update("delete from account where id=?", 5);

        //查询所有
//        List<AccountDay0401> accounts = jt.query("select * from account where money >?", new BeanPropertyRowMapper<>(AccountDay0401.class), 400);
//        for (AccountDay0401 account : accounts) {
//            System.out.println("account = " + account);
//        }
        //1 查询单个,使用查询所有所有中的方法,这也是经常使用的
        List<AccountDay0401> query = jt.query("select * from account where id = ?", new BeanPropertyRowMapper<>(AccountDay0401.class), 1);
        System.out.println("query.get(0) = " + query.get(0));
        //2 queryForObject
//        AccountDay0401 accountDay0401 = jt.queryForObject("select * from account where id =?",
//        new BeanPropertyRowMapper<>(AccountDay0401.class), 2);//
//        System.out.println("accountDay0401 = " + accountDay0401);
      //查询总数
        Long counts = jt.queryForObject("select count(*) from account", long.class);
        System.out.println("counts = " + counts);

    }

}

jdbc注意:


/**
 * @author cat
 * @name [ssmDemo] com.cat.dao.impl /AccountDay0401Impl
 * @create 2021-01-19 11:33
 * 继承jdbcDaosupport,可以不用写jdbctemplate,和set方法,都在JdbcDaoSupport中,继承不能使用注解配置,不继承可以
 *      @Autowired
 *     private JdbcTemplate jdbcTemplate;
 */
public class AccountDay0401Impl02 extends JdbcDaoSupport implements AccountDao {
    
    
    @Override
    public AccountDay0401 findAccountById(Integer id) {
        List<AccountDay0401> query = getJdbcTemplate().query("select * from account where id =?", new BeanPropertyRowMapper<>(AccountDay0401.class), id);
        return query.isEmpty() ? null : query.get(0);
    }

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

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

spring-transaction

xml方式配置

步骤

  1. 配置事务管理器

  2. 配置事务通知

  3. 配置AOP通用切入点表达式

  4. 建立事务通知和切入点表达式的关系

  5. 配置事务通知属性

<?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:tx="http://www.springframework.org/schema/tx"
       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/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">

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

    <!-- 配置账户的持久层-->
    <bean id="accountDao" class="com.cat.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 name="url" value="jdbc:mysql://localhost:3306/eesy_spring?useSSL=false"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--
    spring中基于xml的声明式事务控制
        1.配置事务管理器
        2.配置事务通知
        3.配置Aop中的通用切入点表达式
        4.建立事务通知和切入点表达式的关系
        5.配置事务的属性
    -->

<!--    1.配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

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

    <aop:config>
        <!--3.配置aop切入点表达式-->
        <aop:pointcut id="pt1" expression="execution(* com.cat.service.impl.*.*(..))"/>
        <!--4.建立事务通知和切入点表达式的联系-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>

事务的annotation支持

步骤

  1. 配置事务管理器

  2. 开启事务注解支持

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


    <!--配置包扫描-->
    <context:component-scan base-package="com.cat"/>
    <!--配置JDBCTemplate类-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>

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


    <!--
         spring中基于XML的声明式事务控制配置步骤
        1.配置事务管理器
        2.开启事务注解支持
     -->

    <!--1. 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--2.开启事务注解支持-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>

注意:JdbcDaoSupport

1.注解开发时dao实现层不能继承JdbcDaoSupport来使用jdbcTemplate,使用了则不能使用注解

2.注解开发使用JDBCTemplate时,在容器记得添加jdbcTemplate类

package com.cat.dao.impl;

import com.cat.dao.IAccountDao;
import com.cat.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 账户的持久层实现类
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    
    @Autowired
    private JdbcTemplate jdbcTemplate;

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

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

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

事务配置

package com.cat.service.impl;

import com.cat.dao.IAccountDao;
import com.cat.domain.Account;
import com.cat.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 账户的业务层实现类
 *
 * 事务控制应该都是在业务层
 */
@Service
@Transactional
//默认propagation="REQUIRED",read-only="false"可以不写,针对增删改
public class AccountServiceImpl implements IAccountService{

    @Autowired
    private IAccountDao accountDao;

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

    @Override
    @Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
    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);
    }
}

annotation方式配置

SpringConfig.java

@Configuration
@ComponentScan("com.cat")
@Import({JdbcConfig.class, TransactionConfig.class})
@EnableTransactionManagement
public class SpringConfig {
}

jdbcConfig.java

@Configuration
@PropertySource("classpath:jdbc.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;


    @Bean("jdbcTemplate}")
    public JdbcTemplate createJdbcTemplate(DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean("dataSource")
    public DataSource getDataSource() {
        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
        driverManagerDataSource.setDriverClassName(driver);
        driverManagerDataSource.setUrl(url);
        driverManagerDataSource.setUsername(username);
        driverManagerDataSource.setPassword(password);
        return driverManagerDataSource;
    }
}

TransactionConfig.java

@Configuration
public class TransactionConfig {

    @Bean("transactionManager")
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        return new DataSourceTransactionManager(dataSource);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值