【Spring】Jdbc Template(小型轻量级持久化层框架)细致分析与实战应用

笔记大纲
  • JdbcTemplate简介

  • JdbcTemplate应用步骤

    • 导入JAR包
    • 数据库中创建测试表
    • 创建数据连接的db.properties属性文件
    • 创建配置spring-jdbc.xml文件
  • 创建单元测试,进行CRUD(持久化操作)

  • 使用JdbcTemplate实现Dao

    • spring-jdbc.xml文件中组件扫描操作
    • 创建StudentDao类,注入JdbcTemplate
    • 在测试类TestJdbcTemplate注入StudentDao,进行测试
    • 运行结果

1.JdbcTemplate简介

ORM:(object Relational mapping )顾名思义:对象关系映射!是一种为了解决面向对象与关系型数据库存在不匹配现象的技术,简单说,orm通过描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系型数据库中!

  为了使JDBC更加易于使用,Spring在JDBC API上定义了一个抽象层,以此建立一个JDBC存取框架。

  作为Spring JDBC框架的核心,JDBC模板的设计目的是为不同类型的JDBC操作提供模板方法,通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。

  Spring的JdbcTemplate可看作是一个小型的轻量级持久化层框架,与DBUtils风格非常接近,与MyBatis框架相比,使用的频率还是很低,之前应用的SSH框架还是比较多!

2.JdbcTemplate应用步骤
2.1.导入JAR包

(1)IOC容器所需要的JAR包【5个】

commons-logging-1.1.1.jar

spring-beans-4.0.0.RELEASE.jar

spring-context-4.0.0.RELEASE.jar

spring-core-4.0.0.RELEASE.jar

spring-expression-4.0.0.RELEASE.jar

(2)JdbcTemplate所需要的JAR包【3个】

spring-jdbc-4.0.0.RELEASE.jar

spring-orm-4.0.0.RELEASE.jar

spring-tx-4.0.0.RELEASE.jar

(3) 数据库驱动和数据源【2个】

druid-1.1.9.jar

mysql-connector-java-5.1.7-bin.jar

(4)为了单元测试方便,导入spring提供的对测试框架支持的jar包(白盒测试),【1个】

spring-test-4.0.0.RELEASE.jar1

2.2.数据库中创建测试表

在这里插入图片描述

2.3.创建数据连接的db.properties属性文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/codinglin_jdbctemplate
jdbc.username=root
jdbc.password=root
2.4.创建配置spring-jdbc.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-4.0.xsd">
	
	<!-- 读取外部的 属性配置文件-->
	<context:property-placeholder location="classpath:db.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>
    
	<!-- 配置JdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="datasource"></property>
	</bean>

</beans>

3.创建单元测试,进行CRUD(持久化操作)
package com.codinglin.spring.beans;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)//指定Spring的运行环境
@ContextConfiguration("classpath:spring-jdbc.xml") //指定Spring的配置文件
public class TestJdbcTemplate {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	/*
	 * 测试增删改功能:jdbcTemplate.update()
	 * 
	 */
	@Test
	public void test() {
		System.out.println(jdbcTemplate);
		//org.springframework.jdbc.core.JdbcTemplate@13c10b87
	}
	@Test
	public void testUpdate01() {
		//增加操作
		String sql="insert into stu_info_table(stu_name,gender,college) values(?,?,?)";
		jdbcTemplate.update(sql, "林大侠",0,"Java学院");
		
	}
	@Test
	public void testUpdate02() {
		//修改操作
		String sql="update stu_info_table  set stu_name= ? where id =1";
		jdbcTemplate.update(sql, "林大侠侠");
		
	}
	@Test
	public void testUpdate03() {
		//删除操作
		String sql="delete from  stu_info_table  where id =?";
		jdbcTemplate.update(sql, "1");
		
	}
	/*
	 * 测试批量增删改功能:jdbcTemplate.batchUpdate()
	 * 
	 */
	@Test
	public void testBatchUpdate() {
		String sql="insert into stu_info_table(stu_name,gender,college)  values(?,?,?)";
		ArrayList<Object[]> batchArgs = new ArrayList<Object[]>();
		batchArgs.add(new Object[] {"钢铁侠",1,"人工智能学院"});
		batchArgs.add(new Object[] {"神奇侠",0,"大数据学院"});
		batchArgs.add(new Object[] {"猪猪侠",1,"动画学院"});
		jdbcTemplate.batchUpdate(sql, batchArgs);
		
	}
	/*
	 * 查询单行,返回JavaBean对象
	 * RowMapper<Student>的泛型指定了queryForObject()的返回值类型
	 * Student.class:将查询的记录转换为哪种类型
	 * 
	 */
	@Test
	public void testQueryForObjectReturnBean() {
		String sql ="select id,stu_name,gender,college from stu_info_table where id=?";
		RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
		//stu_name查询出的结果是stuName,这是Java的语法,“驼峰命名法”!!
		Student student = jdbcTemplate.queryForObject(sql, rowMapper,2);
		System.out.println(student);
		//Student [id=2, stuName=林大侠, gender=0, college=Java学院]
	}
	/*
	 * 查询的单个值
	 * 
	 */
	@Test
	public void testQueryForObjectReturnSingleValue() {
		String sql="select count(id) from stu_info_table";
		Integer num = jdbcTemplate.queryForObject(sql, Integer.class);
		System.out.println("查询stu_info_table表的记录数:"+num);
		//查询stu_info_table表的记录数:5
	}
	/*
	 * 查询多行
	 * 
	 */
	@Test
	public void testQuery() {
		String sql="select id,stu_name,gender,college from stu_info_table";
		RowMapper<Student> rowMapper = new BeanPropertyRowMapper<Student>(Student.class);
		List<Student> students = jdbcTemplate.query(sql, rowMapper);
		System.out.println(students);
		/*[Student [id=2, stuName=林大侠, gender=0, college=Java学院], 
		 Student [id=3, stuName=钢铁侠, gender=1, college=人工智能学院],
		 Student [id=4, stuName=神奇侠, gender=0, college=大数据学院],
		 Student [id=5, stuName=猪猪侠, gender=1, college=动画学院], 
		 Student [id=6, stuName=林大侠, gender=0, college=Java学院]]*/
	}
}                                   

总结:

  (1)增删改:jdbcTemplate.update(String,Object...)

  (2)批量增删改:jdbcTemplate.batchUpdate(String List<Object[]>)

​    Object[]封装SQL语句中每一次执行时所需要的参数;

     List集合封装了SQL语句多次执行时所有的参数。

  (3)查询单行:jdbcTemplate.queryForObject(String, RowMapper<Student>,Object...)

  (4)查询单一值:jdbcTemplate.queryForObject(String, Class,Object...)

  (5)查询多行:jdbcTemplate.query(String, RowMapper<Student>,Object....)

4.使用JdbcTemplate实现Dao

  通过IOC容器自动注入,JdbcTemplate类是线程安全的,则可在IOC容器中饭声明它的单例,注入到所有的Dao实例中!

4.1.spring-jdbc.xml文件中组件扫描操作
	<!--扫描组件-->
	<context:component-scan base-package="com.codinglin.spring.beans"></context:component-scan>
	
	<!-- 读取外部的 属性配置文件-->
	<context:property-placeholder location="classpath:db.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>
	
	<!-- 配置JdbcTemplate -->
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="datasource"></property>
	</bean>

</beans>
4.2.创建StudentDao类,注入JdbcTemplate
@Repository
public class StudentDao {
	@Autowired
	private JdbcTemplate jdbcTemplate;
	public void insertStudent(Student stu) {
		String sql="insert into stu_info_table(stu_name,gender,college) values(?,?,?)";
		jdbcTemplate.update(sql,stu.getStuName(),stu.getGender(),stu.getCollege());	
	}
}
4.3.在测试类TestJdbcTemplate注入StudentDao,进行测试
    @Autowired
	private StudentDao StudentDao;
	@Test
	public void testStudentDao() {
		Student student= new Student();
		student.setStuName("csdn");
		student.setGender(1);
		student.setCollege("csdn学院");
		StudentDao.insertStudent(student);
		
	}
4.4.运行结果

在这里插入图片描述


 ☝上述分享来源个人总结,如果分享对您有帮忙,希望您积极转载;如果您有不同的见解,希望您积极留言,让我们一起探讨,您的鼓励将是我前进道路上一份助力,非常感谢!我会不定时更新相关技术动态,同时我也会不断完善自己,提升技术,希望与君同成长同进步!

☞本人博客:https://coding0110lin.blog.csdn.net/  欢迎转载,一起技术交流吧!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值