spring框架(五)之JdbcTemplate基本使用

数据准备

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>spring5</artifactId><version>1.0-SNAPSHOT</version><name>spring5</name><properties><maven.compiler.target>1.8</maven.compiler.target><maven.compiler.source>1.8</maven.compiler.source><junit.version>5.7.1</junit.version></properties><dependencies><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-api</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter-engine</artifactId><version>${junit.version}</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.19</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.2.1</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.0.6.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>5.0.5.RELEASE</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.13.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.13.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.1</version></dependency><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency></dependencies><build><plugins></plugins></build>
</project>

1.1 JdbcTemplate概述

它是spring框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装。spring框架为我们提供了很多的操作 模板类。例如:操作关系型数据的JdbcTemplate和HibernateTemplate,操作nosql数据库的RedisTemplate,操 作消息队列的JmsTemplate等等。

1.2 JdbcTemplate开发步骤

1 导入spring-jdbc和spring-tx坐标

<!--导入spring的jdbc坐标-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.0.5.RELEASE</version>
</dependency> 
<!--导入spring的tx坐标-->
<dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.0.5.RELEASE</version>
</dependency>

2 创建数据库表和实体
3 创建JdbcTemplate对象
4 执行数据库操作

1.3 JdbcTemplate快速入门

在数据库中准备好数据

 

public class test {//测试jdbc@Testpublic void test1() throws PropertyVetoException {//创建数据源对象ComboPooledDataSource dataSource = new ComboPooledDataSource();dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day17");dataSource.setUser("root");dataSource.setPassword("12345678");JdbcTemplate jdbcTemplate = new JdbcTemplate();//设置数据源jdbcTemplate.setDataSource(dataSource);//执行语句int row = jdbcTemplate.update("insert into day22 value ( ?,? ,? ) ", null,"lisi", "123456");System.out.println(row);}
}

1.4 Spring产生JdbcTemplate对象 

我们可以将JdbcTemplate的创建权交给Spring,将数据源DataSource的创建权也交给Spring,在Spring容器内部将 数据源DataSource注入到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"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--    配置数据源对象--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="com.mysql.cj.jdbc.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day17"/><property name="user" value="root"/><property name="password" value="12345678"/></bean><!--    配置JDBC模板对象--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean></beans>

    @Testpublic void test2(){ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");JdbcTemplate jdbcTemplate = app.getBean(JdbcTemplate.class);int row = jdbcTemplate.update("insert into day22 value ( ?,? ,? ) ", null,"mazi", "123456");System.out.println(row);}

继续抽取配置applicationContext.xml文件,减少耦合性

  • 创建jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/day17
jdbc.name=root
jdbc.password=12345678
  • 在applicationContext.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:property-placeholder location="jdbc.properties"/><!--    配置数据源对象--><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"/><property name="jdbcUrl" value="${jdbc.url}"/><property name="user" value="${jdbc.name}"/><property name="password" value="${jdbc.password}"/></bean><!--    配置JDBC模板对象--><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="dataSource"/></bean></beans>

 

package com.study.test;import com.study.doman.Users;
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.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;/*** @author Alina* @date 2022年03月30日 7:14 下午*/
//使用spring集成Junit进行测试
@RunWith(SpringJUnit4ClassRunner.class)
//指定配置文件
@ContextConfiguration("classpath:applicationContext.xml")
public class jdbcTemplateTest {//注入对象@Autowiredprivate JdbcTemplate jdbcTemplate;@Testpublic void test1(){int row = jdbcTemplate.update("update day22 set password = ? where username = ?", 123123, "tom");System.out.println(row);}@Testpublic void test2(){int row = jdbcTemplate.update("delete from day22 where username = ?",  "tom");System.out.println(row);}//查询全部@Testpublic void test3(){List<Users> User = jdbcTemplate.query("select * from day22", new BeanPropertyRowMapper<Users>(Users.class));System.out.println(User);}//查询一个@Testpublic void test4(){Users user = jdbcTemplate.queryForObject("select * from day22 where username = ?", new BeanPropertyRowMapper<>(Users.class), "张三");System.out.println(user);}@Test//查询行数public void test5(){Long user = jdbcTemplate.queryForObject("select count(*) from day22 where username = ?", Long.class, "张三");System.out.println(user);}}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/421631.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Jquery表单插件ajaxForm用法详解

插件主要的方法&#xff1a; ajaxFormajaxSubmitformToArrayformSerialize fieldSerializefieldValueclearFormclearFieldsresetForm 示例代码&#xff1a; 1// wait for the DOM to be loaded2$(document).ready(function() { 3 // bind myForm and provide a simple callba…

icp光谱仪的工作原理_icp直读光谱仪-3秒快速了解原理步骤[博越仪器]

icp直读光谱仪&#xff0c;又名电感耦合等离子体光谱仪&#xff0c;属于光谱仪的一大分支&#xff0c;主要用于检测微量及衡量元素的分析&#xff0c;可分析的元素为大多数的金属元素&#xff0c;具体的检测元素因为不同厂家采用的核心配件不同而不同&#xff0c;如5代光谱仪就…

spring框架(六)之拦截器

一. SpringMVC拦截器 1.1 拦截器(interceptor)的作用 Spring MVC 的拦截器类似于 Servlet 开发中的过滤器 Filter&#xff0c;用于对处理器进行预处理和后处理。 将拦截器按一定的顺序联结成一条链&#xff0c;这条链称为拦截器链(Interceptor Chain)。在访问被拦截的方 法或…

c# AutoResetEvent和ManualResetEvent

网上有很多AutoResetEvent和ManualResetEvent的详细介绍&#xff0c;在这里不做过多详细的解释&#xff0c;写下自己的一点心得留作备忘。 AutoResetEvent和ManualResetEvent都是事件锁&#xff0c;事件的功能就是可以在被监控者发生某种变化后立即通知监控者并做出相应反应。 …

取最大值_查找数组中最大值的5种方法!(动图演示)

我们在一些特定场景下&#xff0c;例如查询公司员工的最高薪资&#xff0c;以及班级的最高成绩又或者是面试中都会遇到查找最大值的问题&#xff0c;所以本文我们就来列举一下查询数组中最大值的 5 种方法。首先我们来看最原始也是最“笨”的实现方法&#xff1a;循环对比和递归…

hdu 3405 world islands

求删点后最小的生成树&#xff0c;n<50.。。。数据好弱&#xff0c;直接暴力枚举就行。。。删点的时候直接g[i][j]INF就行了。 #include<iostream> #include<algorithm> #include<fstream> #include<string> #include<vector> #include<st…

文件跟随_如何在苹果Mac上将文件合并为PDF?推荐收藏

当有不同页面合并到一个文档中时&#xff0c;可能需要合并PDF文件&#xff0c;那么如何在苹果Mac电脑上将文件合并为PDF&#xff1f;其实您可以在电脑上直接合并&#xff0c;操作非常简单&#xff0c;当然如果您有其他要求&#xff0c;比如说多个pdf文件的合并&#xff0c;需要…

python 之多进程+队列复制

# Time : 2022/11/10 10:40 # Author : 阿紫 # File : 多进程复制文件.py # Description : import multiprocessing import osdef copy_file(old_folder_name,file_name,new_folder_name,queue):"""复制文件"""# 旧文件地址old_path ope…

windows下eclipse搭建android_ndk开发环境

1、安装cygwin&#xff1a; 由于NDK编译代码时必须要用到make和gcc&#xff0c;所以你必须先搭建一个linux环境&#xff0c; cygwin是一个在windows平台上运行的unix模拟环境,它对于学习unix/linux操作环境&#xff0c;或者从unix到windows的应用程序移植&#xff0c;非常有用。…

svn update中文报错_svn 更新文件冲突,提示中文乱码解决(示例代码)

问题描述&#xff1a;update 操作提示错误信息&#xff0c;中文乱码 和 “Please execute the ‘Cleanup‘ command.”Cleanup 操作报错&#xff1a;解决办法&#xff1a;1. 工具下载(sqlite3.exe)&#xff1a;链接&#xff1a;https://pan.baidu.com/s/1OXWMZPCsmRNEe3FluIdRu…

IE(=8)版本不支持getElementsByClassName()

IE(<8)版本不支持getElementsByClassName()转载于:https://www.cnblogs.com/leamiko/p/3195800.html

linux翻页查看命令_在 Linux 命令行使用 more 查看文本文件

文本文件和 Linux 一直是携手并进的。或者说看起来如此。那你又是依靠哪些让你使用起来很舒服的工具来查看这些文本文件的呢&#xff1f;-- Scott NesbittLinux 下有很多实用工具可以让你在终端界面查看文本文件。其中一个就是 more 。more 跟我之前另一篇文章里写到的工具 ——…

数据类型、常量、变量

c语言本身只是一门语言&#xff0c; 程序是为了让机器执行而写的代码 为了让机器明白我们的意思&#xff0c;于是c 产生了&#xff08;虎躯一震&#xff0c;王霸之气肆意啊&#xff09; Just like the language that we have learned ——English&#xff0c;学E文时候 各种语法…

python输出空心等腰三角形_python学习,打印等腰直角三角形 实心正方形空心正方形...

在学习python的过程中&#xff0c;自己做了一个小练习#!/usr/bin/python# -*- coding: utf-8 -*-name input("请输入数字&#xff1a; ")count int(name)count2 int(name)#空心正方形while (count > 0):for i in range(count2):if count count2:print *,elif …