Spring_jdbcTemplate

任务三:Spring JDBCTemplate & 声明式事 务

一 JdbcTemplate

  • JdbcTemplate是spring框架中提供的一个模板对象,是对原始繁琐的Jdbc API对象的简单封装。
  • 核心对象:
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource);
  • 核心方法:
int update(); 执行增、删、改语句
    
List<T> query(); 查询多个
T queryForObject(); 查询一个
new BeanPropertyRowMapper<>(); 实现ORM映射封装
  • 代码实例:
    • 往数据库中新增一条数据
@Repository
public class ArticleDaoImpl implements ArticleDao {

    @Autowired//由容器中返回
    private JdbcTemplate    jdbcTemplate;

    //添加文章信息
    public void saveArticle(Article article) {
         String sql="insert into t_article (title,content)values(?,?)";
         //int i=7/0;
         jdbcTemplate.update(sql, article.getTitle(), article.getContent());
    }
}
  • 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"
	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/context
		http://www.springframework.org/schema/context/spring-context.xsd">
  <!--注解扫描-->  
<context:component-scan base-package="com.lagou"/>
  <!--加载properties数据库配置文件-->    
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
	<property name="driverClassName" value="${jdbc.driver}"></property>
	<property name="url" value="${jdbc.url}"></property>
	<property name="username" value="${jdbc.username}"></property>
	<property name="password" value="${jdbc.password}"></property>
</bean>
    
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
</bean>
</beans>

二 Spring的事务

2.1Spring中的事务控制方式

  • Spring的事务控制可以分为编程式事务控制声明式事务控制

  • 编程式事务:

    • 直接把事务的代码和业务代码耦合到一起,在实际开发中不用。
  • 声明式事务:

    • 采用配置的方式来实现的事务控制,业务代码与事务代码实现解耦合,使用的AOP思想

2.2基于XML的声明式事务控制

  • 明确事项:
    1. 核心业务代码(目标对象) (切入点是谁?)
    2. 事务增强代码(Spring已提供事务管理器))(通知是谁?)
    3. 切面配置(切面如何配置?)
0.步骤分析
1. 引入tx命名空间

2. 事务管理器通知配置

3. 事务管理器AOP配置

1.引入tx命名空间
<?xml version="1.0" encoding="UTF-8"?>
	<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w2.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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/s chema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
    </beans>

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

    <!--通知增强-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--定义事务的一些属性--> 
        <tx:attributes>
            <tx:method name="transfer" isolation="REPEATABLE_READ" propagation="REQUIRED"
                       timeout="-1" read-only="false"/>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
            <!--*表示任意名称方法都走默认配置-->
            <tx:method name="*"/>
            <!--
            * name:切点方法名称
            * isolation:事务的隔离级别
            * propogation:事务的传播行为()
				REQUIRED:如果当前没有事务,就新建一个事务;有则加入事务
				SUPPORTS :没有事务。有就有,没有就没用。
            * timeout:超时时间。默认为-1,否则以秒为单位
            * read-only:是否只读。查询时可设置
            -->
        </tx:attributes>
    </tx:advice>
3.事务管理器AOP配置
<!--配置切面-->
<aop:config>
     <!--aspect用于方法-->
	<aop:advisor advice-ref="txAdvice"
                  pointcut="execution(*com.lagou.service.impl.AccountServiceImpl.*(..))"/>
</aop:config>

2.3基于注解的声明式事务控制

0.步骤分析
1. 修改service层,增加事务注解

2. 修改spring核心配置文件,开启事务注解支持
1.修改service层,增加事务注解
@Service
public class AccountServiceImpl implements AccountService {
	@Autowired
	private AccountDao accountDao;
    
    @Transactional(propagation = Propagation.REQUIRED, isolation =
Isolation.REPEATABLE_READ, timeout = -1, readOnly = false)
	@Override
	public void transfer(String outUser, String inUser, Double money) {
	accountDao.out(outUser, money);
	//int i = 1 / 0;
	accountDao.in(inUser, money);
	}
}
2.修改spring核心配置文件,开启事务注解支持
<!--省略之前datsSource、jdbcTemplate、组件扫描配置-->
	<!--事务的注解支持-->
	<tx:annotation-driven/>
	<!--事务管理器-->
	<bean id="transactionManager"
	class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"></property>
</bean>
3.纯注解式
@Configuration // 声明为spring配置类
@ComponentScan("com.lagou") // 注解扫描
@Import(DataSourceConfig.class) // 导入其他配置类(数据源)
@EnableTransactionManagement // 事务注解驱动
public class SpringConfig {
   
	@Bean//返回JdbcTemplate对象
	public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource) {
	return new JdbcTemplate(dataSource);
  }
	@Bean("transactionManager")//返回事务管理器对象
	public PlatformTransactionManager getPlatformTransactionManager(@Autowired
	DataSource dataSource) {
	return new DataSourceTransactionManager(dataSource);
	}
}
  
  • 数据源配置类
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
	@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//返回连接池对象
	public DataSource getDataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName(driver);
		dataSource.setUrl(url);
		dataSource.setUsername(username);
		dataSource.setPassword(password);
		return dataSource;
}
}

三 Spring集成web环境

3.1ApplicationContext

  • 在使用Spring整合Junit之前,我们使用ApplicationContext应用获取上下文。
    • 代表应用上下文对象,可以获得spring中IOC容器的Bean对象。
     ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");
        Account account = (Account)classPathXmlApplicationContext.getBean("account");
        System.out.println(account);
  • 这样的弊端是配置文件加载多次,应用上下文对象创建多次。

3.2Spring提供获取应用上下文

  • 解决思路分析:

    1. 使用ServletContextListener监听Web应用的启动
    2. 加载配置文件,创建应用上下文对象ApplicationContext,存到servletContext域中
    3. 任意外置获取应用上下文ApplicationContext对象
  • Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供 了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。

3.3实现

  • 在此基础上,我们做两件事:
    1. 在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
    2. 使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
1.导入Spring集成web的坐标
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.1.5.RELEASE</version>
        </dependency>
2.配置ContextLoaderListener监听器
    <!--全局参数 指定application.xml文件路径-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>

    <!--Spring监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
3.获取
//通过工具获得应用上下文对象
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        Account account = (Account)webApplicationContext.getBean("account");
      
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值