Spring系列文章:Spring使用JdbcTemplate

news/2025/2/20 16:54:50/

一、简介

JdbcTemplate是Spring提供的⼀个JDBC模板类,是对JDBC的封装,简化JDBC代码。 当然,你也可以不⽤,可以让Spring集成其它的ORM框架,例如:MyBatis、Hibernate等。

第一步:引入依赖

        <dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>6.0.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13.2</version><scope>test</scope></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!--新增的依赖:spring jdbc,这个依赖中有JdbcTemplate--><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>6.0.2</version></dependency>

二、整合JdbcTemplate

第二步:编写Spring配置⽂件

JdbcTemplate是Spring提供好的类,这类的完整类名是: org.springframework.jdbc.core.JdbcTemplate 我们怎么使⽤这个类呢?new对象就可以了。怎么new对象,Spring最在⾏了。直接将这个类配置到 Spring配置⽂件中,纳⼊Bean管理即可。

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"></bean>

 

可以看到JdbcTemplate中有⼀个DataSource属性,这个属性是数据源,我们都知道连接数据库需要 Connection对象,⽽⽣成Connection对象是数据源负责的。

所以我们需要给JdbcTemplate设置数据源 属性。 所有的数据源都是要实现javax.sql.DataSource接⼝的。这个数据源可以⾃⼰写⼀个,也可以⽤写好的, ⽐如:阿⾥巴巴的德鲁伊连接池,c3p0,dbcp等。我们这⾥⾃⼰先⼿写⼀个数据源。

public class MyDataSource implements DataSource {// 添加4个属性private String driver;private String url;private String username;private String password;// 提供4个setter⽅法public void setDriver(String driver) {this.driver = driver;}public void setUrl(String url) {this.url = url;}public void setUsername(String username) {this.username = username;}public void setPassword(String password) {this.password = password;}// 重点写怎么获取Connection对象就⾏。其他⽅法不⽤管。@Overridepublic Connection getConnection() throws SQLException {try {Class.forName(driver);Connection conn = DriverManager.getConnection(url, username, password);return conn;} catch (Exception e) {e.printStackTrace();}return null;}@Overridepublic Connection getConnection(String username, String password) throws SQLException {return null;}@Overridepublic PrintWriter getLogWriter() throws SQLException {return null;}@Overridepublic void setLogWriter(PrintWriter out) throws SQLException {}@Overridepublic void setLoginTimeout(int seconds) throws SQLException {}@Overridepublic int getLoginTimeout() throws SQLException {return 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {return null;}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {return null;}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {return false;}
}

 写完数据源,我们需要把这个数据源传递给JdbcTemplate。因为JdbcTemplate中有⼀个DataSource属 性:

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><bean id="myDataSource" class="com.springcode.example.entity.MyDataSource"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/spring6"/><property name="username" value="root"/><property name="password" value="root"/></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="myDataSource"/></bean>
</beans>

三、增删改查

1、增加


public class SpringTest {@Testpublic void test(){// 获取JdbcTemplate对象ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);/*注意:insert delete update的sql语句,都是执⾏update⽅法。update⽅法有两个参数:第⼀个参数:要执⾏的SQL语句。(SQL语句中可能会有占位符 ? )第⼆个参数:可变⻓参数,参数的个数可以是0个,也可以是多个。⼀般是SQL语句中有⼏个问号,则对应⼏个参数。*/String sql = "insert into t_user(id,real_name,age) values(?,?,?)";int count = jdbcTemplate.update(sql, null, "张三", 30);System.out.println("插⼊的记录条数:" + count);}
}

2、修改

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏更新操作String sql = "update t_user set real_name = ?, age = ? where id = ?";int count = jdbcTemplate.update(sql, "张三丰", 55, 1);System.out.println("更新的记录条数:" + count);}
}

3、删除

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏deleteString sql = "delete from t_user where id = ?";int count = jdbcTemplate.update(sql, 1);System.out.println("删除了⼏条记录:" + count);}
}

4、查询一个对象

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏selectString sql = "select id, real_name, age from t_user where id = ?";/*queryForObject⽅法三个参数:第⼀个参数:sql语句第⼆个参数:Bean属性值和数据库记录⾏的映射对象。在构造⽅法中指定映射的对象类型。第三个参数:可变⻓参数,给sql语句的占位符问号传值。*/User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 2);System.out.println(user);}
}

5、查询多个对象

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏selectString sql = "select id, real_name, age from t_user";List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));System.out.println(users);}
}

6、查询⼀个值

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 执⾏selectString sql = "select count(1) from t_user";Integer count = jdbcTemplate.queryForObject(sql, int.class); // 这⾥⽤Integer.class也可以System.out.println("总记录条数:" + count);}
}

7、批量添加

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 批量添加String sql = "insert into t_user(id,real_name,age) values(?,?,?)";Object[] objs1 = {null, "⼩花", 20};Object[] objs2 = {null, "⼩明", 21};Object[] objs3 = {null, "⼩刚", 22};List<Object[]> list = new ArrayList<>();list.add(objs1);list.add(objs2);list.add(objs3);int[] count = jdbcTemplate.batchUpdate(sql, list);System.out.println(Arrays.toString(count));}
}

8、批量修改

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 批量修改String sql = "update t_user set real_name = ?, age = ? where id = ?";Object[] objs1 = {"⼩花11", 10, 2};Object[] objs2 = {"⼩明22", 12, 3};Object[] objs3 = {"⼩刚33", 9, 4};List<Object[]> list = new ArrayList<>();list.add(objs1);list.add(objs2);list.add(objs3);int[] count = jdbcTemplate.batchUpdate(sql, list);System.out.println(Arrays.toString(count));}
}

9、批量删除

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);// 批量删除String sql = "delete from t_user where id = ?";Object[] objs1 = {2};Object[] objs2 = {3};Object[] objs3 = {4};List<Object[]> list = new ArrayList<>();list.add(objs1);list.add(objs2);list.add(objs3);int[] count = jdbcTemplate.batchUpdate(sql, list);System.out.println(Arrays.toString(count));}
}

10、使⽤回调函数

public class SpringTest {@Testpublic void test(){ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);String sql = "select id, real_name, age from t_user where id = ?";User user = jdbcTemplate.execute(sql, new PreparedStatementCallback<User>() {@Overridepublic User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {User user = null;ps.setInt(1, 5);ResultSet rs = ps.executeQuery();if (rs.next()) {user = new User();user.setId(rs.getInt("id"));user.setRealName(rs.getString("real_name"));user.setAge(rs.getInt("age"));}return user;}});System.out.println(user);}
}

四、使⽤德鲁伊连接池

上面数据源是⽤我们⾃⼰写的。也可以使⽤别⼈写好的。例如⽐较⽜的德鲁伊连接池。

第⼀步:引⼊德鲁伊连接池的依赖。

<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.8</version>
</dependency>

第⼆步:将德鲁伊中的数据源配置到spring配置⽂件中。和配置我们⾃⼰写的⼀样。

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource"><property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/spring6"/><property name="username" value="root"/><property name="password" value="root"/></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"><property name="dataSource" ref="druidDataSource"/></bean>
</beans>

测试


public class SpringTest {@Testpublic void test(){// 获取JdbcTemplate对象ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);String sql = "insert into t_user(id,real_name,age) values(?,?,?)";int count = jdbcTemplate.update(sql, null, "张三", 30);System.out.println("插⼊的记录条数:" + count);}
}


http://www.ppmy.cn/news/1096048.html

相关文章

java 整合 swagger-ui 步骤

1.在xml 中添加Swagger 相关依赖 <!-- springfox-swagger2 --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><!-- springfox-swa…

【excel密码】excel文件加密方法总结:

想要给Excel文件进行加密&#xff0c;方法有很多&#xff0c;今天分享三种Excel加密方法给大家。 打开密码 设置了打开密码的excel文件&#xff0c;打开文件就会提示输入密码才能打开excel文件&#xff0c;只有输入了正确的密码才能打开并且编辑文件&#xff0c;如果密码错误…

qt多个信号如何关联一并处理

主要方法&#xff1a; 首先&#xff0c;需要创建一个包含自定义信号和槽的Qt类。假设要创建一个名为MyObject的类&#xff0c;并在其中定义一个自定义信号和一个槽。这个类的头文件可能如下所示&#xff1a; #ifndef MYOBJECT_H #define MYOBJECT_H#include <QObject>c…

索尼 toio™应用创意开发征文|一步两步三步模拟浇花系统

目录 1.toio™介绍 2、创意分析 2.1 创意设计 2.2 创意落地 3、创意实现 3.1 环境安装 3.2 核心玩法 总结 1.toio™介绍 索尼的toio™是一款启发创意的机器人产品&#xff0c;旨在通过与真实世界的互动&#xff0c;为各年龄段的用户提供娱乐体验。这款产品具有高度的灵…

第4章:网络层

文章目录 一、概述和功能2.SDN二、转发1.IP数据报(1)IP数据报的首部字段(2)IP数据报的分片2.IPv4地址:<网络号>,<主机号>3.IP编址 (三个历史阶段)(1)分类IP地址①特殊IP地址②私有IP地址③网络地址转换NAT:导致IP地址变化MAC地址、IP地址变化问题(2)子网划分与子…

谷歌收录网页最快需要多久?

答案是&#xff1a;谷歌收录网页最快是24小时内。 当我们建立新的网站或者为现有网站添加新内容时&#xff0c;都希望这些内容能够尽快被谷歌收录。 但实际上&#xff0c;谷歌的收录时间可能会因各种因素而异。 这篇文章将为您详解相关的知识点。 网站收录的基本过程 如何…

云备份服务端——实用类工具实现

一&#xff0c;文件实用类设计实现 不管是客户端还是服务端&#xff0c;文件的传输备份都涉及到文件的读写&#xff0c;包括数据管理信息的持久化也是如此&#xff0c;因此首先设计封装文件操作类&#xff0c;这个类封装完毕之后&#xff0c;则在任意模块中对文件进行操作时都将…

图的深度优先与广度优先遍历

上篇博客介绍了图的概念与图的存储(邻接矩阵、邻接表)&#xff1a; 接下来就是介绍图的遍历。 图的遍历 给定一个图G和其中任意一个顶点v0&#xff0c;从v0出发&#xff0c;沿着途中各边访问图中的所有顶点&#xff0c;且每个顶点仅被遍历一次。"遍历"即对结点进行…