一、概述

  Spring的数据访问层是以统一的数据访问异常层体系为核心,结合JDBC API的最佳实践和统一集成各种ORM方案,完成Java平台的数据访问。

二、JDBC API的最佳实践

  Spring提供两种JDBC API的最佳实践,一种是以JDBCTemplate为核心的基于Template的JDBC使用方式,另一种则是在JdbcTemplate基础之上构建的基于操作对象的JDBC使用方式。

  1、基于Template的JDBC使用方式

  Spring框架提出了org.springframework.jdbc.core.JdbcTemplate作为数据访问的Helper类,JDBCTemplate是整个Spring数据抽象层提供的所有JDBC API最佳实践的基础。

  jdbcTemplate主要关注以下事情:

  • 封装所有基于JDBC的数据访问代码,以统一格式和规范来使用JDBC API。
  • 对SQLException所提供的异常信息在框架内进行统一转译,统一了数据接口的定义,简化了客户端代码对数据访问异常的处理。

  下面简单介绍JdbcTemplate的使用示例。

  首先是在Spring的IoC容器中配置数据源和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. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
  7.  
  8. <context:property-placeholder location="classpath:db.properties"/>
  9. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
  10. <property name="driverClass" value="${jdbc.driver}"/>
  11. <property name="jdbcUrl" value="${jdbc.url}"/>
  12. <property name="user" value="${jdbc.username}"/>
  13. <property name="password" value="${jdbc.password}"/>
  14. </bean>
  15. <!-- 配置Spring的JdbcTemplate -->
  16. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
  17. <property name="dataSource" ref="dataSource"></property>
  18. </bean>
  19. </beans>

  其中,db.properties内容为:

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/student?characterEncoding=utf-8
  3. jdbc.username=root
  4. jdbc.password=281889

  接下来就可以编写测试类:

  1. public class JDBCTest
  2. {
  3. private ApplicationContext applicationContext=null;
  4. private JdbcTemplate jdbcTemplate;
  5. {
  6. applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
  7. jdbcTemplate=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
  8. }
  9. @Test
  10. public void test()
  11. {
  12. DataSource dataSources=applicationContext.getBean(DataSource.class);
  13. System.out.println(dataSources.toString());
  14. }
  15. /**
  16. * 根据id查询用户信息
  17. */
  18. @Test
  19. public void testFindUserById()
  20. {
  21. String sql="select * from User where id=2";
  22.  
  23. Map<String, Object> map=jdbcTemplate.queryForMap(sql);
  24. for(String s:map.keySet())
  25. {
  26. System.out.println(s+":"+map.get(s));
  27. }
  28. }
  29. /**
  30. * 查到实体类集合
  31. */
  32. @Test
  33. public void testQueryForList()
  34. {
  35. String sql="select * from User where id>?";
  36. RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
  37. List<User> list=jdbcTemplate.query(sql, rowMapper,2);
  38. for (User user : list)
  39. {
  40. System.out.println(user.getUsername());
  41. }
  42. }
  43. /**
  44. * 从数据库中获取一条记录,实际得到对应的一个对象
  45. */
  46. @Test
  47. public void getUserById()
  48. {
  49. String sql="select * from User where id=?";
  50. RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
  51. User user=jdbcTemplate.queryForObject(sql, rowMapper,1);
  52. System.out.println(user.getUsername());
  53. }
  54. /**
  55. * 统计查询
  56. */
  57. @Test
  58. public void testQueryForCount()
  59. {
  60. String sql="select count(id) from user";
  61. long count=jdbcTemplate.queryForObject(sql, Long.class);
  62. System.out.println(count);
  63. }
  64. }

  2、基于操作对象的JDBC使用方式

  Spring除了提供基于Template形式的JDBC形式,还对各种数据库操作以面向对象的形式进行建模。在这种基于操作对象的JDBC使用方式中,查询、更新、调用存储过程等数据访问操作,被抽象为操作对象,这些操作对象统一定义在org.springframework.jdbc.object包下。

三、Spring对ORM的集成

  Spring对当前各种流行的ORM解决方案的集成主要体现在以下几个方面:

  • 统一的资源管理方式
  • 特定于ORM的数据访问异常到Spring统一异常体系的转译
  • 统一的数据访问事务管理及控制方式

  1、Spring对Mybatis的集成

  实现mybatis和Spring进行整合,通过Spring管理SqlSessionFactory、mapper接口。

  整个需要的jar包:

  

  构建Myba配置文件:

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--加载映射文件
  7. 使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers
  8. -->
  9. <mappers>
  10. <package name="com.demo.ssm.mapper"/>
  11. </mappers>

  构建Spring配置文件:

  在classpath下创建applicationContext.xml,定义数据库链接池、SqlSessionFactory。

  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:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
  7.  
  8. <context:property-placeholder location="classpath:db.properties"/>
  9. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
  10. <property name="driverClassName" value="${jdbc.driver}"/>
  11. <property name="url" value="${jdbc.url}"/>
  12. <property name="username" value="${jdbc.username}"/>
  13. <property name="password" value="${jdbc.password}"/>
  14. <property name="maxActive" value="10"/>
  15. <property name="maxIdle" value="5"/>
  16. </bean>
  17. <!-- sqlSessionFactory -->
  18. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  19. <!--加载mybatis的配置文件 -->
  20. <property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
  21. <!-- 数据源 -->
  22. <property name="dataSource" ref="dataSource"></property>
  23. </bean>
  24. </beans>

  编写Mapper,这里有三种方法

  • 第一种方法:Dao接口实现类继承SqlSessionDaoSupport

  使用此种方法即原始dao开发方法,需要编写dao接口,dao接口实现类、映射文件。

  1、sqlMapConfig.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--加载映射文件
  7. 使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers
  8. -->
  9. <mappers>
  10. <mapper resource="sqlmap/User.xml"/>
  11. </mappers>
  12. </configuration>

  2、定义dao接口

  1. public interface UserDao
  2. {
  3. public User getUserById(int id) throws Exception;
  4.  
  5. }

  3、dao接口实现类继承SqlSessionDaoSupport

  1. public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao
  2. {
  3. public User getUserById(int id) throws Exception
  4. {
  5. // 继承SqlSessionDaoSupport
  6. SqlSession session = this.getSqlSession();
  7. User user = null;
  8. // 通过sqlsession调用selectOne方法获取一条结果集
  9. // 参数1:指定定义的statement的id,参数2:指定向statement中传递的参数
  10. user = session.selectOne("test.findUserById", id);
  11. return user;
  12. }
  13. }

  4、Spring配置文件

  1.   <!-- 原始dao接口 -->
  2. <bean id="userDao" class="com.demo.ssm.dao.UserDaoImpl">
  3. <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
  4. </bean>

  5、编写测试类测试运行

  1. public class UserDaoImplTest
  2. {
  3. private ApplicationContext applicationContext;
  4. @Before
  5. public void setup()
  6. {
  7. applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
  8. }
  9. @Test
  10. public void testGetUserById() throws Exception
  11. {
  12. UserDao userDao=(UserDao) applicationContext.getBean("userDao");
  13. User user=userDao.getUserById(1);
  14. System.out.println(user);
  15. }
  16. }
  • 第二种方法:使用org.mybatis.spring.mapper.MapperFactoryBean

  此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。每个mapper接口都需要在spring配置文件中定义

  1、在sqlMapConfig.xml中配置mapper.xml的位置

  如果mapper.xml和mappre接口的名称相同且在同一个目录,这里可以不用配置

  2、定义mapper接口

  1. public interface UserMapper
  2. {
  3. //根据用户id查询用户信息
  4. public User findUserById(int id) throws Exception;
  5. }

  3、Spring中定义

  1. <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  2. <property name="mapperInterface" value="com.demo.ssm.mapper.UserMapper"></property>
  3. <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
  4. </bean>

  4、编写测试类测试运行

  1. public class UserMapperTest
  2. {
  3. private ApplicationContext applicationContext;
  4. @Before
  5. public void setup()
  6. {
  7. applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
  8. }
  9. @Test
  10. public void testGetUserById() throws Exception
  11. {
  12. UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
  13. User user=userMapper.findUserById(1);
  14. System.out.println(user);
  15. }
  16. }
  • 第三种方法:使用mapper扫描器

  此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。只需要在spring配置文件中定义一个mapper扫描器,自动扫描包中的mapper接口生成代代理对象。

  1、mapper.xml文件编写

  2、定义mapper接口

  注意:mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录

  3、配置mapper扫描器

  1. <!-- mapper批量扫描,从mapper包中扫描成mapper接口,自动创建 代理对象并在Spring容器中注册
  2. 自动扫描出来的mapper的bean的id为mapper类型(首字母小写)
  3. -->
  4. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  5. <!-- 指定扫描的包名 -->
  6. <property name="basePackage" value="com.demo.ssm.mapper"></property>
  7. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  8. </bean>

Spring系列之访问数据库的更多相关文章

  1. Spring Boot入门教程2-1、使用Spring Boot+MyBatis访问数据库(CURD)注解版

    一.前言 什么是MyBatis?MyBatis是目前Java平台最为流行的ORM框架https://baike.baidu.com/item/MyBatis/2824918 本篇开发环境1.操作系统: ...

  2. Spring实战6:利用Spring和JDBC访问数据库

    主要内容 定义Spring的数据访问支持 配置数据库资源 使用Spring提供的JDBC模板 写在前面:经过上一篇文章的学习,我们掌握了如何写web应用的控制器层,不过由于只定义了SpitterRep ...

  3. Spring 定时器 定时访问数据库并发送邮件

    我这里有两个案例的方法: 第一种:使用Spring quartz: 我这里使用的jar:spring-context-support.jar.quartz-1.6.5.jar ============ ...

  4. Springboot 系列(十)使用 Spring data jpa 访问数据库

    前言 Springboot data jpa 和 Spring jdbc 同属于 Spring开源组织,在 Spring jdbc 之后又开发了持久层框架,很明显 Spring data jpa 相对 ...

  5. Spring系列之不同数据库异常如何抽象的?

    前言 使用Spring-Jdbc的情况下,在有些场景中,我们需要根据数据库报的异常类型的不同,来编写我们的业务代码.比如说,我们有这样一段逻辑,如果我们新插入的记录,存在唯一约束冲突,就会返回给客户端 ...

  6. Spring系列

    Spring系列之访问数据库   阅读目录 一.概述 二.JDBC API的最佳实践 三.Spring对ORM的集成 回到顶部 一.概述 Spring的数据访问层是以统一的数据访问异常层体系为核心,结 ...

  7. spring boot访问数据库

    1. Spring JAP 基本使用说明: Spring boot 访问数据库基本上都是通过Spring JPA封装的Bean作为API的,Spring JPA 将访问数据库通过封装,只要你的类实现了 ...

  8. Spring Boot实战之数据库操作

    上篇文章中已经通过一个简单的HelloWorld程序讲解了Spring boot的基本原理和使用.本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是Jdb ...

  9. Spring Boot(二):数据库操作

    本文主要讲解如何通过spring boot来访问数据库,本文会演示三种方式来访问数据库,第一种是JdbcTemplate,第二种是JPA,第三种是Mybatis.之前已经提到过,本系列会以一个博客系统 ...

随机推荐

  1. JUnit介绍,JUnit是什么?

    JUnit是什么? JJUnit是用于编写和运行可重复的自动化测试的开源测试框架, 这样可以保证我们的代码按预期工作.JUnit可广泛用于工业和作为支架(从命令行)或IDE(如Eclipse)内单独的 ...

  2. ym——Android开发MVP模式(攻克了View和Model的耦合)

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103),谢谢支持! 什么是MVP呢?它又和我们经常听到的MVC有什么关系了以及差别呢? MVP 是从经典的 ...

  3. 互联网公司GitHub repo 语言使用情况

    转自: https://laike9m.com/blog/hu-lian-wang-gong-si-github-repo-yu-yan-shi-yong-qing-kuang,56/ 现在基本上所有 ...

  4. t4 根据表名数组生成实体

    <#@ template debug="false" hostspecific="true" language="C#" #> ...

  5. Java注解Annotation学习笔记

    一.自定义注解 1. 使用关键字 @interface 2. 默认情况下,注解可以修饰 类.方法.接口等. 3. 如下为一个基本的注解例子: //注解中的成员变量非常像定义接口 public @int ...

  6. mysql replace into用法详细说明

    From: http://www.cnblogs.com/martin1009/archive/2012/10/08/2714858.html REPLACE的运行与INSERT很相似.只有一点例外, ...

  7. 精挑细选 8款HTML5/jQuery应用助网站走向高上大

    在WEB3.0的时代,我们的网站不仅要实现实用价值,更要为用户设计优秀的用户体验.jQuery是一个不错的JS框架,结合目前最新的HTML5技术,我们可以将自己的网站脱胎换骨,立马走向高上大,至少在前 ...

  8. 1. 请问PHP里的ECHO是什么意思 ?请问PHP里的ECHO是什么意思???有什么作用???又应该怎么使用???

    直接输出字符或字符串的意思: 例如:echo "abc"; 就会输出abc echo 'abc' 一样是输出abc . 如果仅仅只输出字符串的话,单引号和双引号是输出内容是一样的, ...

  9. c++ String去除头尾空格

    1.使用string的find_first_not_of,和find_last_not_of方法 #include <iostream> #include <string> s ...

  10. Android中利用C++处理Bitmap对象

    相信有些Android&图像算法开发者和我一样,遇到过这样的状况:要对Bitmap对象做一些密集计算(例如逐像素的滤波),但是在java层写循环代码来逐像素操作明显是不现实的,因为Java代码 ...