Spring系列
Spring系列之访问数据库
一、概述
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。

<?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-4.1.xsd"> <context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置Spring的JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

其中,db.properties内容为:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?characterEncoding=utf-8
jdbc.username=root
jdbc.password=281889
接下来就可以编写测试类:

public class JDBCTest
{
private ApplicationContext applicationContext=null;
private JdbcTemplate jdbcTemplate;
{
applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
jdbcTemplate=(JdbcTemplate) applicationContext.getBean("jdbcTemplate");
}
@Test
public void test()
{
DataSource dataSources=applicationContext.getBean(DataSource.class);
System.out.println(dataSources.toString());
}
/**
* 根据id查询用户信息
*/
@Test
public void testFindUserById()
{
String sql="select * from User where id=2"; Map<String, Object> map=jdbcTemplate.queryForMap(sql);
for(String s:map.keySet())
{
System.out.println(s+":"+map.get(s));
}
}
/**
* 查到实体类集合
*/
@Test
public void testQueryForList()
{
String sql="select * from User where id>?";
RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
List<User> list=jdbcTemplate.query(sql, rowMapper,2);
for (User user : list)
{
System.out.println(user.getUsername());
}
}
/**
* 从数据库中获取一条记录,实际得到对应的一个对象
*/
@Test
public void getUserById()
{
String sql="select * from User where id=?";
RowMapper<User> rowMapper=new BeanPropertyRowMapper<>(User.class);
User user=jdbcTemplate.queryForObject(sql, rowMapper,1);
System.out.println(user.getUsername());
}
/**
* 统计查询
*/
@Test
public void testQueryForCount()
{
String sql="select count(id) from user";
long count=jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
}

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配置文件:

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

构建Spring配置文件:
在classpath下创建applicationContext.xml,定义数据库链接池、SqlSessionFactory。

<?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-4.1.xsd"> <context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxActive" value="10"/>
<property name="maxIdle" value="5"/>
</bean>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml"></property>
<!-- 数据源 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

编写Mapper,这里有三种方法
- 第一种方法:Dao接口实现类继承SqlSessionDaoSupport
使用此种方法即原始dao开发方法,需要编写dao接口,dao接口实现类、映射文件。
1、sqlMapConfig.xml配置文件

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

2、定义dao接口
public interface UserDao
{
public User getUserById(int id) throws Exception; }
3、dao接口实现类继承SqlSessionDaoSupport

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

4、Spring配置文件
<!-- 原始dao接口 -->
<bean id="userDao" class="com.demo.ssm.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
5、编写测试类测试运行

public class UserDaoImplTest
{
private ApplicationContext applicationContext;
@Before
public void setup()
{
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testGetUserById() throws Exception
{
UserDao userDao=(UserDao) applicationContext.getBean("userDao");
User user=userDao.getUserById(1);
System.out.println(user);
}
}

第二种方法:使用org.mybatis.spring.mapper.MapperFactoryBean
此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。每个mapper接口都需要在spring配置文件中定义
1、在sqlMapConfig.xml中配置mapper.xml的位置
如果mapper.xml和mappre接口的名称相同且在同一个目录,这里可以不用配置
2、定义mapper接口
public interface UserMapper
{
//根据用户id查询用户信息
public User findUserById(int id) throws Exception;
}
3、Spring中定义
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.demo.ssm.mapper.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
4、编写测试类测试运行

public class UserMapperTest
{
private ApplicationContext applicationContext;
@Before
public void setup()
{
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testGetUserById() throws Exception
{
UserMapper userMapper=(UserMapper) applicationContext.getBean("userMapper");
User user=userMapper.findUserById(1);
System.out.println(user);
}
}

- 第三种方法:使用mapper扫描器
此方法即mapper接口开发方法,只需定义mapper接口,不用编写mapper接口实现类。只需要在spring配置文件中定义一个mapper扫描器,自动扫描包中的mapper接口生成代代理对象。
1、mapper.xml文件编写
2、定义mapper接口
注意:mapper.xml的文件名和mapper的接口名称保持一致,且放在同一个目录
3、配置mapper扫描器

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

Spring系列的更多相关文章
- Spring 系列: Spring 框架简介 -7个部分
Spring 系列: Spring 框架简介 Spring AOP 和 IOC 容器入门 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级 ...
- Spring 系列: Spring 框架简介
Spring AOP 和 IOC 容器入门(转载) 在这由三部分组成的介绍 Spring 框架的系列文章的第一期中,将开始学习如何用 Spring 技术构建轻量级的.强壮的 J2EE 应用程序.dev ...
- Spring 系列: Spring 框架简介(转载)
Spring 系列: Spring 框架简介 http://www.ibm.com/developerworks/cn/java/wa-spring1/ Spring AOP 和 IOC 容器入门 在 ...
- 通俗化理解Spring3 IoC的原理和主要组件(spring系列知识二总结)
♣什么是IoC? ♣通俗化理解IoC原理 ♣IoC好处 ♣工厂模式 ♣IoC的主要组件 ♣IoC的应用实例 ♣附:实例代码 1.什么是IoC(控制反转)? Spring3框架的核心是实现控制反转(Io ...
- 【SSH框架】之Spring系列(一)
微信公众号:compassblog 欢迎关注.转发,互相学习,共同进步! 有任何问题,请后台留言联系! 1.前言 前面更新过几篇关于 Struts2 框架和 Hibernate 框架的文章,但鉴于这两 ...
- Spring系列之手写一个SpringMVC
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 Spring系列之AOP的原理及手动实现 Spring系列之手写注解与配置文件的解析 引言 在前面的几个章节中我 ...
- Spring系列(七) Spring MVC 异常处理
Servlet传统异常处理 Servlet规范规定了当web应用发生异常时必须能够指明, 并确定了该如何处理, 规定了错误信息应该包含的内容和展示页面的方式.(详细可以参考servlet规范文档) 处 ...
- 狗鱼IT教程:推介最强最全的Spring系列教程
Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson创建. 简单来说,Spring是一个分层的JavaSE/EEfull-stack( ...
- Spring系列之IOC的原理及手动实现
目录 Spring系列之IOC的原理及手动实现 Spring系列之DI的原理及手动实现 导语 Spring是一个分层的JavaSE/EE full-stack(一站式) 轻量级开源框架.也是几乎所有J ...
随机推荐
- 450A - Jzzhu and Children 找规律也能够模拟
挺水的一道题.规律性非常强,在数组中找出最大的数max,用max/m计算出倍数t,然后再把数组中的书都减去t*m,之后就把数组从后遍历找出第一个大于零的即可了 #include<iostream ...
- Android架构分析之使用自定义硬件抽象层(HAL)模块
作者:刘昊昱 博客:http://blog.csdn.net/liuhaoyutz Android版本:2.3.7_r1 Linux内核版本:android-goldfish-2.6.29 在上一篇博 ...
- [Android学习笔记]Android中多线程开发的一些概念
线程安全: 在多线程的情况下,不会因为线程之间的操作而导致数据错误. 线程同步: 同一个资源,可能在同一时间被多个线程操作,这样会导致数据错误.这是一个现象,也是一个问题,而研究如何解决此类问题的相关 ...
- JVM查找类文件的顺序(转)
配置classpath 根据path环境变量的原理,可以定义一个名为classpath环境变量,将要运行的class文件所在目录定义在该变量中. 例:set classpath=c:\ classpa ...
- Cocos2d-x 创建(create)动画对象CCAnimation报错分析
本人在使用精灵表单创建动画的过程中突然遇到了一些个问题,下面进行一下分析总结. 根据在Cocos2d-iphone中的经验,我写出了如下的代码: CCSpriteFrameCache::sharedS ...
- hibernate学习(一)
一.准备工作:导入jar包 1.hibernate的jar包 位置: hibernate-release-5.0.2.Final\hibernate-release-5.0.2.Final\lib\r ...
- linux中vsftpd配置文件详解
vsftpd配置文件采用“#”作为注释符,以“#”开头的行和空白行在解析时将被忽略,其余的行被视为配置命令行,每个配置命令的“=”两边不要留有空格.对于每个配置命令,在配置文件中还列出了相关的配置说明 ...
- UVa 10616 - Divisible Group Sums
称号:给你n数字.免去m一个,这使得他们可分割d.问:有多少种借贷. 分析:dp,D01背包. 背包整数分区. 首先.整点d.则全部数字均在整数区间[0,d)上: 然后,确定背包容量,最大为20*10 ...
- HDU 1498 50 years, 50 colors(最小点覆盖,坑称号)
50 years, 50 colors Problem Description On Octorber 21st, HDU 50-year-celebration, 50-color balloons ...
- 图片本地预览 flash html5
dataURI 一种能够在页面嵌入外部资源的URI方案.能够降低图片或者样式表的http请求数量,提高效率. ie8把dataURI 的属性值限制在32k以内. 图片本地预览: 由于安全原因,通过fi ...