Spring:JdbcTemplate、声明式事务

目录

JdbcTemplate

常用API

示例代码

声明式事务

声明式事务与编程式事务的区别

基于xml实现

抽象类JdbcDaoSupport

基于注解实现


JdbcTemplate

一个简单、轻薄的Jdbc的封装工具。

常用API

  • JdbcTemplate jdbcTemplate= new JdbcTemplate(DataSource dataSource);    构造方法
  • update("sql",Object args...)    增删改操作
  • query("sql',new BeanPropertyRowMapper<>(),Object args...)    查询所有(返回的是list)
  • queryForObject("sql",BeanPropertyRowMapper<>(),Object arg);     查询单个数据(可以将一组数据封装成对象,也可以使用聚合函数查询)

示例代码

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///db_2"/>
        <property name="username" value=""/>
        <property name="password" value=""/>
    </bean>
    <!--    配置jdbcTemplate-->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>
</beans>

测试代码

@Test
    public void t9(){
//        获取容器
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-jdbc.xml");
//        从容器中获取Bean对象
        JdbcTemplate jdbctemplate = context.getBean("jdbctemplate", JdbcTemplate.class);
//        jdbctemplate的使用
//        增加数据
        jdbctemplate.update("insert into user5 values (?,?)","Bob",789);
//        删除数据
        jdbctemplate.update("delete from user5 where name=?","tom");
//        修改数据(更新数据)
        jdbctemplate.update("update user5 set name=?,money=? where name=?","tony",2000,"tony");
//        查询所有
        List<user> query = jdbctemplate.query("select * from user5", new BeanPropertyRowMapper<>(user.class));
        System.out.println(query);
//        查询单个数据(方法一)
        List<user> bob = jdbctemplate.query("select * from user5 where name=?", new BeanPropertyRowMapper<>(user.class), "Bob");
        System.out.println(bob.get(0));
//        查询单个数据(方法二)
        user bob1 = jdbctemplate.queryForObject("select * from user5 where name=?", new BeanPropertyRowMapper<>(user.class), "Bob");
        System.out.println(bob1);
//        使用聚合函数
        Long integer = jdbctemplate.queryForObject("select count(*) from user5",Long.class);
        System.out.println(integer);

    }

声明式事务

声明式事务与编程式事务的区别

编程式事务:代码冗余严重,例如每个方法都需要做同样的增强,那需要对每个方法编程

声明式事务:抽取共同内容,例如每个方法都需要做同样的增强,只需要将增强的代码写一次即可,实现了系统层和业务逻辑层的解耦

基于xml实现

步骤:

  • 配置事务管理器
  • 配置事务通知
  • 配置AOP
<?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/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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
<!--    配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///db_2"/>
        <property name="username" value=""/>
        <property name="password" value=""/>
    </bean>
<!--    配置jdbcTemplate-->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>
<!--    配置dao-->
    <bean id="dao" class="dom8.dao.impl.daoimpl">
        <property name="jdbcTemplate" ref="jdbctemplate"/>
    </bean>
<!--    配置service-->
    <bean id="server" class="dom8.service.impl.serviceeimpl">
        <property name="idao" ref="dao"/>
    </bean>
    
    
<!--    配置事务管理器-->
    <bean id="treanManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
<!--    配置事务通知-->
    <tx:advice id="txAdive" transaction-manager="treanManager">
<!--        配置事务的属性-->
        <tx:attributes>
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>
<!--    配置AOP-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* dom8.service.impl.*.*(..))"/>
<!--        织入:将切点表达式和事务通知建立联系-->
        <aop:advisor advice-ref="txAdive" pointcut-ref="pt1"/>
    </aop:config>
    <aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

注意:

配置事务的属性

需要修改的方法:<tx:method name="*" read-only="false"  propagation="REQUIRED"/>

需要查询的方法:<tx:method name="find*" read-only="true"  propagation="SUPPORTS"/>

属性:

  • read-only:是否只读
  • isolation:指定事务的隔离级别,默认使用数据库的默认隔离级别
  • propagation:事务的传播行为
    • REQUIRED(默认值):如果当前没有事务,就创建一个新的事务,如果已经存在一个事务就加到这个事务中
    • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行
  • timeout:设置超时时间
  • rollback-for:用于指定一个异常,当执行时产生该异常,事务回滚;没有默认值,任何异常都回滚
  • no-rollback-for:用于指定一个异常,当执行时产生该异常,事务不回滚;没有默认值,任何异常都回滚

抽象类JdbcDaoSupport

持久层实现类基础该抽象类,直接调用getJdbcTemplate方法,来获取JdbcTemplate对象

节省了以下代码

 private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

注意:该方法只能使用在基于xml实现的声明式事务中

示例代码

public class daoimpl extends JdbcDaoSupport implements Idao {

    @Override
    public void update(user user) {
       getJdbcTemplate().update("update user5 set name=?,money=? where name=?",user.getName(),user.getMoney(),user.getName());

    }

    @Override
    public user getByName(String name) {
        user user = getJdbcTemplate().queryForObject("select * from user5 where name=?", new BeanPropertyRowMapper<>(user.class), name);
        return user;
    }
}

配置文件:给其注入数据源即可

<bean id="dao" class="dom8.dao.impl.daoimpl">
       <property name="dataSource" ref="dataSource"/>
</bean>

基于注解实现

注解名称

含义
@Transactional配置该类对事务的通知
@EnableTransactionManagement

 开启事务注解(加在配置类上)

应用场景:纯注解配置时使用

步骤

  • 配置事务管理器
  • 开启事务注解
  • 对需要使用事务的类上 加上该注解

示例代码

配置文件

<?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/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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <context:component-scan base-package="dom8"/>
<!--    配置spring内置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///db_2"/>
        <property name="username" value="root"/>
        <property name="password" value="110120"/>
    </bean>
<!--    配置jdbcTemplate-->
    <bean id="jdbctemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>

<!--    配置事务管理器-->
    <bean id="treanManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!--    开启注解-->
    <tx:annotation-driven transaction-manager="treanManager"/>
</beans>

类上使用注解

@Transactional(readOnly = false ,propagation = Propagation.REQUIRED)
@Component("service")
public class serviceeimpl implements Iservice {

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值