Spring—学习笔记#day04

Spring

Posted by DiCaprio on August 6, 2019

目录

1、spring中的JdbcTemplate[会用]

JdbcTemplate的作用

JdbcTemplate对象的创建

spring中配置数据源

在spring配置文件中配置 JdbcTemplate

最基本使用

使用xml文件

  保存、更新、删除、查询操作

在dao中使用 JdbcTemplate

第二种方式:让dao继承 JdbcDaoSupport

2、Spring中的事务控制

Spring事务控制我们要明确的

Spring中事务控制的 API 

PlatformTransactionManager

TransactionDefinition

TransactionStatus

基于XML的声明式事务控制(配置方式)重点

环境配置

配置步骤

基于注解的配置方式

环境配置

配置步骤

不使用 xml 的配置方式


1、spring中的JdbcTemplate[会用]

JdbcTemplate的作用

它就是用于和数据库交互的,实现对表的CRUD操作

它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多
的操作模板类。
操作关系型数据的:
JdbcTemplate
HibernateTemplate
操作 nosql 数据库的:
RedisTemplate
操作消息队列的:
JmsTemplate
我们今天的主角在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包
外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。

JdbcTemplate对象的创建

我们可以参考它的源码,来一探究竟:
public JdbcTemplate() {
}
public JdbcTemplate(DataSource dataSource) {
setDataSource(dataSource);
afterPropertiesSet();
}
public JdbcTemplate(DataSource dataSource, boolean lazyInit) {
setDataSource(dataSource);
setLazyInit(lazyInit);
afterPropertiesSet();
}
除了默认构造函数之外,都需要提供一个数据源。既然有set方法,依据我们之前学过的依赖注入,我们可以
在配置文件中配置这些对象。

spring中配置数据源

在spring配置文件中配置 JdbcTemplate

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <!-- 配置账户的持久层-->
  7. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
  8. <!--<property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
  9. <property name="dataSource" ref="dataSource"></property>
  10. </bean>
  11. <!--配置JdbcTemplate
  12. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  13. <property name="dataSource" ref="dataSource"></property>
  14. </bean>-->
  15. <!-- 配置数据源-->
  16. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  17. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  18. <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
  19. <property name="username" value="root"></property>
  20. <property name="password" value="1234"></property>
  21. </bean>
  22. </beans>

最基本使用

  1. /**
  2. * JdbcTemplate的最基本用法
  3. */
  4. public class JdbcTemplateDemo1 {
  5. public static void main(String[] args) {
  6. //准备数据源:spring的内置数据源
  7. DriverManagerDataSource ds = new DriverManagerDataSource();
  8. ds.setDriverClassName("com.mysql.jdbc.Driver");
  9. ds.setUrl("jdbc:mysql://localhost:3306/eesy");
  10. ds.setUsername("root");
  11. ds.setPassword("1234");
  12. //1.创建JdbcTemplate对象
  13. JdbcTemplate jt = new JdbcTemplate();
  14. //给jt设置数据源
  15. jt.setDataSource(ds);
  16. //2.执行操作
  17. jt.execute("insert into account(name,money)values('ccc',1000)");
  18. }
  19. }

使用xml文件

  1. public class JdbcTemplateDemo2 {
  2. public static void main(String[] args) {
  3. //1.获取容器
  4. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  5. //2.获取对象
  6. JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
  7. //3.执行操作
  8. jt.execute("insert into account(name,money)values('ddd',2222)");
  9. }
  10. }

  保存、更新、删除、查询操作

  1. /**
  2. * JdbcTemplate的CRUD操作
  3. */
  4. public class JdbcTemplateDemo3 {
  5. public static void main(String[] args) {
  6. //1.获取容器
  7. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  8. //2.获取对象
  9. JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
  10. //3.执行操作
  11. //保存
  12. // jt.update("insert into account(name,money)values(?,?)","eee",3333f);
  13. //更新
  14. // jt.update("update account set name=?,money=? where id=?","test",4567,7);
  15. //删除
  16. // jt.update("delete from account where id=?",8);
  17. //查询所有
  18. // List<Account> accounts = jt.query("select * from account where money > ?",new AccountRowMapper(),1000f);
  19. // List<Account> accounts = jt.query("select * from account where money > ?",new BeanPropertyRowMapper<Account>(Account.class),1000f);
  20. // for(Account account : accounts){
  21. // System.out.println(account);
  22. // }
  23. //查询一个
  24. // List<Account> accounts = jt.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),1);
  25. // System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));
  26. //查询返回一行一列(使用聚合函数,但不加group by子句)
  27. Long count = jt.queryForObject("select count(*) from account where money > ?",Long.class,1000f);
  28. System.out.println(count);
  29. }
  30. }
  31. /**
  32. * 定义Account的封装策略
  33. */
  34. class AccountRowMapper implements RowMapper<Account>{
  35. /**
  36. * 把结果集中的数据封装到Account中,然后由spring把每个Account加到集合中
  37. * @param rs
  38. * @param rowNum
  39. * @return
  40. * @throws SQLException
  41. */
  42. @Override
  43. public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
  44. Account account = new Account();
  45. account.setId(rs.getInt("id"));
  46. account.setName(rs.getString("name"));
  47. account.setMoney(rs.getFloat("money"));
  48. return account;
  49. }
  50. }

在dao中使用 JdbcTemplate

  1. public class JdbcTemplateDemo4 {
  2. public static void main(String[] args) {
  3. //1.获取容器
  4. ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
  5. //2.获取对象
  6. IAccountDao accountDao = ac.getBean("accountDao",IAccountDao.class);
  7. Account account = accountDao.findAccountById(1);
  8. System.out.println(account);
  9. account.setMoney(30000f);
  10. accountDao.updateAccount(account);
  11. }
  12. }
  1. /**
  2. * 账户的持久层实现类
  3. */
  4. @Repository
  5. public class AccountDaoImpl2 implements IAccountDao {
  6. @Autowired
  7. private JdbcTemplate jdbcTemplate;
  8. @Override
  9. public Account findAccountById(Integer accountId) {
  10. List<Account> accounts = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
  11. return accounts.isEmpty()?null:accounts.get(0);
  12. }
  13. @Override
  14. public Account findAccountByName(String accountName) {
  15. List<Account> accounts = jdbcTemplate.query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
  16. if(accounts.isEmpty()){
  17. return null;
  18. }
  19. if(accounts.size()>1){
  20. throw new RuntimeException("结果集不唯一");
  21. }
  22. return accounts.get(0);
  23. }
  24. @Override
  25. public void updateAccount(Account account) {
  26. jdbcTemplate.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  27. }
  28. }

有个小问题。就是我们的 dao 有很多时,每个 dao 都有一些重复性的代码。下面就是重复代码:
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;

第二种方式:让dao继承 JdbcDaoSupport

  1. /**
  2. * 账户的持久层实现类
  3. */
  4. public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao {
  5. @Override
  6. public Account findAccountById(Integer accountId) {
  7. List<Account> accounts = super.getJdbcTemplate().query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
  8. return accounts.isEmpty()?null:accounts.get(0);
  9. }
  10. @Override
  11. public Account findAccountByName(String accountName) {
  12. List<Account> accounts = super.getJdbcTemplate().query("select * from account where name = ?",new BeanPropertyRowMapper<Account>(Account.class),accountName);
  13. if(accounts.isEmpty()){
  14. return null;
  15. }
  16. if(accounts.size()>1){
  17. throw new RuntimeException("结果集不唯一");
  18. }
  19. return accounts.get(0);
  20. }
  21. @Override
  22. public void updateAccount(Account account) {
  23. super.getJdbcTemplate().update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
  24. }
  25. }

思考:
两版 Dao  有什么区别呢?
答案:
在 第一种在 Dao  类中定义 JdbcTemplate  的方式,适用于所有配置方式(xml  和注解都可以)。
让 第二种让 Dao  继承 JdbcDaoSupport  的方式,只能用于基于 XML 的方式,注解用不了。

2、Spring中的事务控制

Spring事务控制我们要明确的

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

Spring中事务控制的 API 

PlatformTransactionManager

TransactionDefinition

事务的隔离级别

事务的传播行为

REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起。
NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER:以非事务方式运行,如果当前存在事务,抛出异常
NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作

超时时间

默认值是-1,没有超时限制。如果有,以秒为单位进行设置。

是否是只读事务

建议查询时设置为只读。

TransactionStatus

基于XML的声明式事务控制(配置方式)重点

环境配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-jdbc</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-tx</artifactId>
  15. <version>5.0.2.RELEASE</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-test</artifactId>
  20. <version>5.0.2.RELEASE</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>5.1.6</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.aspectj</groupId>
  29. <artifactId>aspectjweaver</artifactId>
  30. <version>1.8.7</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>junit</groupId>
  34. <artifactId>junit</artifactId>
  35. <version>4.12</version>
  36. </dependency>
  37. </dependencies>

配置步骤

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xsi:schemaLocation="
  7. http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/tx
  10. http://www.springframework.org/schema/tx/spring-tx.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd">
  13. <!-- 配置业务层-->
  14. <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
  15. <property name="accountDao" ref="accountDao"></property>
  16. </bean>
  17. <!-- 配置账户的持久层-->
  18. <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
  19. <property name="dataSource" ref="dataSource"></property>
  20. </bean>
  21. <!-- 配置数据源-->
  22. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  23. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  24. <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
  25. <property name="username" value="root"></property>
  26. <property name="password" value="1234"></property>
  27. </bean>
  28. <!-- spring中基于XML的声明式事务控制配置步骤
  29. 1、配置事务管理器
  30. 2、配置事务的通知
  31. 此时我们需要导入事务的约束 tx名称空间和约束,同时也需要aop的
  32. 使用tx:advice标签配置事务通知
  33. 属性:
  34. id:给事务通知起一个唯一标识
  35. transaction-manager:给事务通知提供一个事务管理器引用
  36. 3、配置AOP中的通用切入点表达式
  37. 4、建立事务通知和切入点表达式的对应关系
  38. 5、配置事务的属性
  39. 是在事务的通知tx:advice标签的内部
  40. -->
  41. <!-- 配置事务管理器 -->
  42. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  43. <property name="dataSource" ref="dataSource"></property>
  44. </bean>
  45. <!-- 配置事务的通知-->
  46. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  47. <!-- 配置事务的属性
  48. isolation:用于指定事务的隔离级别。默认值是DEFAULT,表示使用数据库的默认隔离级别。
  49. propagation:用于指定事务的传播行为。默认值是REQUIRED,表示一定会有事务,增删改的选择。查询方法可以选择SUPPORTS。
  50. read-only:用于指定事务是否只读。只有查询方法才能设置为true。默认值是false,表示读写。
  51. timeout:用于指定事务的超时时间,默认值是-1,表示永不超时。如果指定了数值,以秒为单位。
  52. rollback-for:用于指定一个异常,当产生该异常时,事务回滚,产生其他异常时,事务不回滚。没有默认值。表示任何异常都回滚。
  53. no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时事务回滚。没有默认值。表示任何异常都回滚。
  54. -->
  55. <tx:attributes>
  56. <tx:method name="*" propagation="REQUIRED" read-only="false"/>
  57. <tx:method name="find*" propagation="SUPPORTS" read-only="true"></tx:method>
  58. </tx:attributes>
  59. </tx:advice>
  60. <!-- 配置aop-->
  61. <aop:config>
  62. <!-- 配置切入点表达式-->
  63. <aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
  64. <!--建立切入点表达式和事务通知的对应关系 -->
  65. <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor>
  66. </aop:config>
  67. </beans>

基于注解的配置方式

环境配置

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-context</artifactId>
  5. <version>5.0.2.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework</groupId>
  9. <artifactId>spring-jdbc</artifactId>
  10. <version>5.0.2.RELEASE</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework</groupId>
  14. <artifactId>spring-tx</artifactId>
  15. <version>5.0.2.RELEASE</version>
  16. </dependency>
  17. <dependency>
  18. <groupId>org.springframework</groupId>
  19. <artifactId>spring-test</artifactId>
  20. <version>5.0.2.RELEASE</version>
  21. </dependency>
  22. <dependency>
  23. <groupId>mysql</groupId>
  24. <artifactId>mysql-connector-java</artifactId>
  25. <version>5.1.6</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>org.aspectj</groupId>
  29. <artifactId>aspectjweaver</artifactId>
  30. <version>1.8.7</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>junit</groupId>
  34. <artifactId>junit</artifactId>
  35. <version>4.12</version>
  36. </dependency>
  37. </dependencies>

配置步骤

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:aop="http://www.springframework.org/schema/aop"
  5. xmlns:tx="http://www.springframework.org/schema/tx"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop.xsd
  14. http://www.springframework.org/schema/context
  15. http://www.springframework.org/schema/context/spring-context.xsd">
  16. <!-- 配置spring创建容器时要扫描的包-->
  17. <context:component-scan base-package="com.itheima"></context:component-scan>
  18. <!-- 配置JdbcTemplate-->
  19. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  20. <property name="dataSource" ref="dataSource"></property>
  21. </bean>
  22. <!-- 配置数据源-->
  23. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  24. <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
  25. <property name="url" value="jdbc:mysql://localhost:3306/eesy"></property>
  26. <property name="username" value="root"></property>
  27. <property name="password" value="1234"></property>
  28. </bean>
  29. <!-- spring中基于注解 的声明式事务控制配置步骤
  30. 1、配置事务管理器
  31. 2、开启spring对注解事务的支持
  32. 3、在需要事务支持的地方使用@Transactional注解
  33. -->
  34. <!-- 配置事务管理器 -->
  35. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  36. <property name="dataSource" ref="dataSource"></property>
  37. </bean>
  38. <!-- 开启spring对注解事务的支持-->
  39. <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
  40. </beans>

不使用 xml 的配置方式

@Configuration
@EnableTransactionManagement
public class SpringTxConfiguration {
//里面配置数据源,配置 JdbcTemplate,配置事务管理器。在之前的步骤已经写过了。
}


0 comments
Anonymous
Markdown is supported

Be the first person to leave a comment!