• Spring对不同持久化技术进行支持

    • JDBC

      • 导入spring-jdbc-4.3.5.RELEASE.jar、spring-tx-4.3.5.RELEASE.jar
      • 创建对象,设置数据库信息
      • 创建jdbcTemplate对象,设置数据源
      • 调用jdbcTemplate对象里面对方法实现操作
        public class TestDao {/*** 添加指定数据表的数据*/public void insertUser() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句String sql = "insert into user (username,password,email,root,register_time) values (?,?,?,?,?) ";//
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);int rows = jdbcTemplate.update(sql,"rabbit","rabbit","rabbit@qq.com",1,"2019-3-2");System.out.println("rows="+rows);} catch (IOException e) {e.printStackTrace();}}/*** 更新指定数据表的数据*/public void updateUser() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句
                 String sql = "update user set phone = ? where username = ?";//
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);int rows = jdbcTemplate.update(sql,"13812392132","rabbit");System.out.println("rows=" + rows);} catch (IOException e) {e.printStackTrace();}}/*** 查询全部数据*/public void selectAllUser() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句
                  String sql = "select * from user";//
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);System.out.println("maps=" + maps);} catch (IOException e) {e.printStackTrace();}}/*** 删除指定数据*/public void deleteUser() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句
                  String sql = "delete from user where username = ?";//
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);int row = jdbcTemplate.update(sql, "rabbit");System.out.println("row=" + row);} catch (IOException e) {e.printStackTrace();}}/*** 查询指定数据表的记录数*/public void selectCountUser() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句
                 String sql = "select count(*) from user";//
                    JdbcTemplate jdbcTemplate = new JdbcTemplate(driverManagerDataSource);//第一个参数sql语句,第二个参数返回的数据类型Integer count = jdbcTemplate.queryForObject(sql,Integer.class);System.out.println("count=" + count);} catch (IOException e) {e.printStackTrace();}}public void   selectUser();() {try {//导入配置文件InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");//
                    DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();driverManagerDataSource.setJdbcUrl(driver);driverManagerDataSource.setJdbcUrl(url);driverManagerDataSource.setUser(username);driverManagerDataSource.setPassword(password);//数据库语句
                  String sql = "select * from user where username = ?";User user = jdbcTemplate.queryForObject(sql, new NewRowMapper(), "rabbit");JSONObject jsonObject = JSONObject.fromObject(user);System.out.println(jsonObject + "");} catch (IOException e) {e.printStackTrace();}}/*** 处理查询结果集*/class NewRowMapper implements RowMapper<User> {@Overridepublic User mapRow(ResultSet resultSet, int i) throws SQLException {try {Class<?> newClass = Class.forName("cn.muriel.auto.pojo.User");Object o = newClass.newInstance();for (int j = 1; j <= resultSet.getMetaData().getColumnCount(); j++) {String name = resultSet.getMetaData().getColumnName(j);String type = resultSet.getMetaData().getColumnTypeName(j);//针对只有一次_的情况,多次则可用递归if (name.contains("_")) {int position = name.indexOf("_");String smailChar = name.substring(position + 1, position + 2).toUpperCase();name = name.substring(0, position) + smailChar + name.substring(position + 2, name.length());}Field declaredField = newClass.getDeclaredField(name);if (declaredField != null) {declaredField.setAccessible(true);if (type.equals("INT"))declaredField.set(o, resultSet.getInt(name));else if (type.equals("VARCHAR"))declaredField.set(o, resultSet.getString(name));}}return (User) o;} catch (ClassNotFoundException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (NoSuchFieldException e) {e.printStackTrace();}return null;}}}/**
        * 测试代码
        */public static void main(String[] args) {Test01 test01 = (Test01) applicationContext.getBean("test01");test01.test01();*/TestDao dao = new TestDao();dao.insertUser();dao.updateUser();dao.selectAllUser();dao.selectUser();dao.selectCountUser();
        }    

      • spring配置c3p0连接池
        • 导入mchange-commons-java-0.2.11.jar、c3p0-0.9.5.2.jar
        • 连接连接池
          • 代码实现

              InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("db.properties");Properties properties = new Properties();try {properties.load(inputStream);//获取参数String driver = properties.getProperty("jdbc.driver");String url = properties.getProperty("jdbc.url");String username = properties.getProperty("jdbc.username");String password = properties.getProperty("jdbc.password");ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();comboPooledDataSource.setDriverClass(driver);comboPooledDataSource.setJdbcUrl(url);comboPooledDataSource.setUser(username);comboPooledDataSource.setPassword(password);} catch (IOException e) {e.printStackTrace();} catch (PropertyVetoException e) {e.printStackTrace();}

          • 注入实现
            <?xml version="1.0" encoding="UTF-8" ?>
            <!--http://www.springframework.org/schema/context/spring-context.xsd:用于注解的约束-->
            <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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- 自动注入<context:component-scan base-package="cn.muriel.auto.dao"/> --><context:property-placeholder location="db.properties"/><!-- 配置注入 --><bean id="userDao" class="cn.muriel.auto.dao.UserDao"/><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"></property><property name="jdbcUrl" value="${jdbc.url}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean><bean id="testDao" class="cn.muriel.auto.dao.TestDao"><property name="jdbcTemplate" ref="jdbcTemplate"/></bean></beans>

    • Hibernate
    • Ibatis(MyBatis)
    • JPA
  • Spring的事务管理
    • 什么是事务
    • 事务的特性
    • 不考虑隔离性产生读问题
    • 解决读问题
      • 设置隔离级别
    • spring事务管理两种方式
      • 编程式事务管理
      • 声明式事务管理
        • 基于xml配置文件实现

           <!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 注入dataSource --><property name="dataSource" ref="dataSource"/></bean><!-- 配置事务增强 --><tx:advice id="txadvice" transaction-manager="transactionManager"><!-- 做事务操作 --><tx:attributes><!--设置进行事务操作的方法匹配规则name:匹配名字propagation:默认。--><tx:method name="insert*" propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 配置切面 --><aop:config><!-- 切入点 --><aop:pointcut id="pointcut1" expression="* (cn.muriel.auto.service.TestService.*)(..)"/><!-- 切面 --><aop:advisor advice-ref="txadvice" pointcut-ref="pointcut1"/></aop:config>

        • 基于注解实现
            <!-- 配置事务管理器 --><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 注入dataSource --><property name="dataSource" ref="dataSource"/></bean><!-- 配置事务注解 --><tx:annotation-driven transaction-manager="transactionManager"/>/*** 使用事务的方法所在类上面添加注解*/
          @Transactional
          public class TestService {}

    • spring事务管理高层抽象主要包括3个接口
      • PlatformTransactionManager(事务管理器)

        • spring针对不同的dao层框架,提供接口不同的实现类
        • 首先都要配置事务管理器
      • TransactionDefinition(事务定义信息(隔离、传播、超时、只读))
      • TransactionStatus(事务具体运行状态)

转载于:https://www.cnblogs.com/fatRabbit-/p/10562544.html

Spring框架基础(中)相关推荐

  1. 一.Spring框架基础

    JAVAEE框架之Spring 一.Spring框架基础 Spring:春天:轻量级的企业级开发框架,核心是IOC(控制反转)和AOP(面向切面编程). 官网:spring.io Spring–> ...

  2. Spring框架基础知识

    本人博客文章网址:https://www.peretang.com/basic-knowledge-of-spring-framework/ Spring框架简介 Spring , 一个开源的框架 , ...

  3. Spring框架—基础介绍

    原文地址:https://www.cnblogs.com/lagou/p/10552815.html 目录 一.spring基本概念 二.spring框架 三.spring中机制和实现 三.sprin ...

  4. Spring 框架基础(04):AOP切面编程概念,几种实现方式演示

    本文源码:GitHub·点这里 || GitEE·点这里 一.AOP基础简介 1.切面编程简介 AOP全称:Aspect Oriented Programming,面向切面编程.通过预编译方式和运行期 ...

  5. Spring框架基础(2)----Bean的创建及标签属性

    一.实例化Bean的三种方式 ⽅式⼀:使用无参构造函数 在默认情况下,它会通过反射调⽤⽆参构造函数来创建对象.如果类中没有无参构造函数,将创建失败. <bean id="userSer ...

  6. Spring框架基础概念(面试概念解答)

    Spring框架概述 什么是Spring? 三层体系架构 Spring框架的优点 Spring的体系结构 Core Container(核心容器) Data Access/Integration(数据 ...

  7. 第五章spring框架基础

    spring框架 一.spring 概念: 开发步骤: 第1步: 添加jar包 第2步: 创建Java类 第3步: 创建Spring配置文件 第4步: 编写Spring配置文件 二 .控制反转 概念: ...

  8. Spring 框架基础(06):Mvc架构模式简介,执行流程详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.SpringMvc框架简介 1.Mvc设计理念 MVC是一种软件设计典范,用一种业务逻辑.数据.界面显示分离的方法组织代码,将业务逻辑聚集 ...

  9. Spring 框架基础(03):核心思想 IOC 编程说明,案例演示

    本文源码:GitHub·点这里 || GitEE·点这里 一.IOC控制反转 1.IOC容器思想 Java系统中对象耦合关系十分复杂,系统的各模块之间依赖,微服务模块之间的相互调用请求,都是这个道理. ...

  10. Spring 框架基础(02):Bean的生命周期,作用域,装配总结

    本文源码:GitHub·点这里 || GitEE·点这里 一.装配方式 Bean的概念:Spring框架管理的应用程序中,由Spring容器负责创建,装配,设置属性,进而管理整个生命周期的对象,称为B ...

最新文章

  1. C++11中Lambda表达式的使用
  2. CTFshow 命令执行 web44
  3. 一天搞定CSS: 浮动(float)与inline-block的区别--11
  4. 【最小割】HDU 3987 Harry Potter and the Forbidden Forest
  5. vuls漏洞扫描工具
  6. java 类的实例化没有属性值,java – JsonMappingException:无法实例化类型的值没有single-long-arg构造函数/工厂方法...
  7. c++怎么实现数字数组的删除数字_C/C++数据结构:栈结构解析,最简单解析,让你一遍就会...
  8. python类及其方法
  9. 【RUST官方语言中文翻译】前言
  10. 工作感想:浅论Java教学工作
  11. Linux阻塞和同步机制
  12. 前端优化,包括css,jss,img,cookie
  13. Journal of BitcoinJ 从clone开始
  14. relative会脱离文档流吗_抖音投放你会吗?选Feed流还是Dou+?
  15. 云教务学校管理系统源码
  16. 印象笔记粘贴HTML,VScode下MarkDown如何连接印象笔记
  17. Python批量给PDF加图片签名
  18. 区块链交易性能、隐私保护、监管问题
  19. 转载:手机银行技术讨论3
  20. 项目中对微信昵称特殊字符的处理

热门文章

  1. An unhandled exception occurred: listen EADDRNOTAVAIL: address not available
  2. [WUSTCTF2020]alison_likes_jojo
  3. springboot 整合 ueditor 并实现文件上传(自定义上传路径)
  4. windows机器硬盘不能超过2T详解及图文破解方法
  5. win7激活成功 但每次开机后又显示此windows副本不是正版的解决办法
  6. 妖精为什么吃不到唐僧肉
  7. 人工智能(AI)如何彻底改变项目管理
  8. 950个织梦网dede模板源码
  9. SpringMVC复习——B站
  10. windows2008+IIS7部署智遥工作流