Spring_04

Spring 中的 JdbcTemplate

  • JdbcTemplate 概述:它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。

JdbcTemplate入门

  1. 要使用jdbcTemplate需要在pom.xml中先导入坐标
pom.xml
	<!--spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

     <!--事务相关-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
  1. 创建jdbcTemplate对象时需要传入数据源,可以使用带参的构造函数传入数据源,也可以单独设置,既然有set方法,依据我们之前学过的依赖注入,我们可以在配置文件中配置这些对象。
    spring 框架也提供了一个内置数据源,我们也可以使用 spring 的内置数据源,或者其他数据库技术c3p0或者dbcp。
创建JdbcTemplatec对象

01 - 不使用配置的创建方式

/**
 * JdbcTemplate的最基本用法
 */
public class JdbcTemplateDemo1 {
    public static void main(String[] args) {
        //准备数据源,spring的内置数据源
        DriverManagerDataSource ds = new DriverManagerDataSource();
        ds.setDriverClassName("com.mysql.jdbc.Driver");
        ds.setUrl("jdbc:mysql://localhost:3306/eesy?characterEncoding=UTF-8");
        ds.setUsername("root");
        ds.setPassword("root");

        //1 创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate();//或者new的时候直接传ds
        //给jt设置数据源
        jt.setDataSource(ds);
        //2 执行操作
        jt.execute("insert into account(name,money)values ('ccc',1000)");
    }
}

02 - 使用配置注入来创建对象

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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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

    <!--配置数据源 使用spring内置的-->
    <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?characterEncoding=UTF-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>
public class JdbcTemplateDemo2 {
    public static void main(String[] args) {
        //1 获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2 获取对象
        JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
        //3 执行操作
        jt.execute("insert into account(name,money)values ('泡泡',1000)");
    }
}
JdbcTemplatec的crud操作
/**
 * JdbcTemplate的CRUD操作
 */
public class JdbcTemplateDemo3 {
    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 (?,?)","eee",33333);
        //更新
        jt.update("update account set name=?,money=? where id=?","text",123,7);
        //删除
        jt.update("delete from account where id=?",7);
        //查询所有
        //自定义account封装
//      List<Account> list = jt.query("select * from account where money > ?", new AccountRowMapper(), 1000f);
        List<Account> list = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class), 1000f);
        for (Account account : list) {
            System.out.println(account);
        }
        //查询一个(使用查询所有然后返回第一个)
        List<Account> accounts = jt.query("select * from account where id = ?", new BeanPropertyRowMapper<Account>(Account.class), 1);
        System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));

        //查询返回一行一列(聚合函数)
        Long count = jt.queryForObject("select count(*) from account where money > ?", Long.class, 1000);
        System.out.println(count);
    }
}


/**
 * 定义account的封装策略
 */
class AccountRowMapper implements RowMapper<Account>{
    /**
     * 把结果集中的数据封装到account中,由spring把每个account加到集合中
     */
    public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
        Account account = new Account();
        account.setId(rs.getInt("id"));
        account.setName(rs.getString("name"));
        account.setMoney(rs.getFloat("money"));
        return account;
    }

JdbcTemplatec在dao中的使用

其实就是把jdbcTemplate的操作封装到方法中,使用对象调用。

/**
 * 账户的持久性实现类
 */
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); //id是唯一的,要么没有要么一个
    }

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

需要配置dao的bean,注入jdbcTemplate:

 <!--配置账户的持久层-->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"></property>
    </bean>
  • 在将来会有更多的dao,我们可以封装相同的代码,例如获取jdbcTemplate:
  1. 使用xml配置可以选择继承:不可以再自己添加注解,因为是spring内置的代码,只能读。
    在这里插入图片描述
  2. 如果使用注解配置:
    在这里插入图片描述

Spring 中的事务控制

第一:JavaEE 体系进行分层开发,事务处理位于业务层,Spring 提供了分层设计业务层的事务处理解决方案。
第二:spring 框架为我们提供了一组事务控制的接口。这组接口是在spring-tx-5.0.2.RELEASE.jar 中。
第三:spring 的事务控制都是基于 AOP 的,它既可以使用编程的方式实现,也可以使用配置的方式实现。

1 spring中基于xml的声明式事务控制

spring中基于xml的声明式事务控制配置步骤
        1 配置事务管理器
        2 配置事务通知
            此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
            使用tx:advice标签配置事务通知
                属性:
                    id:给事务通知起一个唯一标识
                    transaction-manager:给事务通知提供一个事务管理器引用
        3 配置aop中的通用切入点表达式
        4 建立事务通知和切入点表达式的对应关系
        5 配置事务的属性
            是在事务的通知tx:advice标签的内部:tx:attributes

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


    <!--配置业务层-->
    <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="jdbcTemplate" ref="jdbcTemplate"></property>-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置数据源 使用spring内置的-->
    <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?characterEncoding=UTF-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--配置事务的通知  有提交和回滚-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    	<!--配置事务属性-->
        <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:pointcut>
        <!--建立切入点表达式和事务通知的对应关系-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
    </aop:config>

</beans>

2 spring中基于注解的声明式事务控制

<?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">


    <!--配置spring创建容器时要扫描的包-->
    <context:component-scan base-package="com.itheima"></context:component-scan>

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

    <!--配置数据源 使用spring内置的-->
    <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?characterEncoding=UTF-8"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

    <!--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>

</beans>

在xml的配置上,使用注解会比较简单,但是在业务层方法中,如果有多个方法,有些只读,有些读写,那么配置事务属性@Transactional可能需要写很多次,比较麻烦。

//事务控制应该在业务层
@Service("accountService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class AccountServiceImpl implements IAccountService {

    @Autowired
    private IAccountDao accountDao;

    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
	//可以单独在方法上指定
    @Transactional(propagation = Propagation.REQUIRED,readOnly = false)
    public void transfer(String sourceName, String targetName, Float money) {
       ...
    }
}

纯注解配置:将剩下的xml配置也使用注解来实现

/**
 * 和连接数据库相关的配置类
 */
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")
    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;
    }
}

/**
 * 和事务相关的配置类
 */
public class TransactionConfig {

    //用于创建事务管理器对象
    @Bean(name = "transactionManager")
    public PlatformTransactionManager createTransactionManager(DataSource dataSource){
        //PlatformTransactionManager是一个接口,返回一个new对象
        return new DataSourceTransactionManager(dataSource);
    }
}
/**
 * Spring的配置类,相当于bean.xml
 */
@Configuration
@ComponentScan("com.itheima")
@Import({JdbcConfig.class,TransactionConfig.class})
@PropertySource("jdbcConfig.properties")    //properties文件
@EnableTransactionManagement    //开启注解事务支持
public class SpringConfiguration {

}
/**
 * 使用Junit单元测试,测试我们的配置
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
	...
}
3 spring编程式事务控制(了解)

代码繁琐,一般不使用

 <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务模板对象-->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="transactionManager"></property>
    </bean>
public void transfer(final String sourceName, final String targetName, final Float money) {
        transactionTemplate.execute(new TransactionCallback<Object>() {
            public Object doInTransaction(TransactionStatus status) {
                ...
            }
        });
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值