Spring JdbcTemplate使用

迷南。 2022-05-25 09:29 334阅读 0赞

该篇博客主要阐述关于Spring中jdbcTemplate,jdbcTemplate大大方便了jdbc的一些重复性操作

一、jdbcTemplate更新数据库常用方法

  • update (更新数据)
  • batchUpdate (批量更新数据库)
  • queryForObject (查询单行)
  • query (查询多行)
  • queryForObject (单值查询)不同的

二、Spring提供的数据访问模板,分别适用于不同的持久化机制

其中就包含了该篇博客要阐述的jdbcTemplate

这里写图片描述


三、了解Spring数据访问过程

Spring将数据访问过程中固定的和可变的部分明确划分为两个不同的类

  • 模板(template) :模板管理过程中固定的部分
  • 回调(callback) :回调处理自定义的数据访问代码

四、了解jdbcTemplate

Spring对数据库的操作在jdbc上面做了深层次的封装,使用Spring的注入功能,可以把DataSource(数据库连接池)注册到jdbcTemplate中


五、了解数据库连接池的重要性

1、普通的JDBC连接数据库每次向数据库建立连接的时候都将connection加载到内存,再验证用户名等信息,这样会消耗一定的时间,每次的数据库连接,使用完后再断开,这样的方式会消耗大量的资源和时间。同时上千人访问的话将占用很多系统资源,导致服务器崩溃
2、数据库连接池其实就是一个为数据库连接建立的一个“缓存池”,预先在数据库连接池中放入一定数量的连接。当需要数据库连接时,从连接池中拿就是了,用完再放回。数据库连接池负责分配、管理、释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立
3、数据库连接池在初始化时将创建一定数量的数据库连接放到连接池中(initialPoolSize).无论这些数据库连接是否被使用,连接池都将一直保证至少拥有这么多的连接数量
4、连接池的最大数据库连接数量限定了这个连接池占有的最大连接数(maxPoolSize)。当应用程序向连接池请求的连接数超过最大连接数时,这些请求将加入到等待队列中
5、数据库连接池相对于无连接池的优点
  • 资源重用,避免频繁创建
  • 更快的系统反应速度
  • 实现某一应用最大可用数据库连接数的限制避免某一应用独占所有的数据库资源
  • 统一的连接管理,避免数据库连接泄露
6、常用的数据库连接池
  • c3p0(常用)
  • dbcp
  • proxool

六、Spring中实现jdbcTemplate对数据库操作(采用c3p0连接池)

1、首先导入JAR

主要是不要忘了c3p0连接池的jar和数据库的jar

2、src下创建属性配置文件db.properties

  • 基本信息配置

    1. - jdbc.user=root
    2. - jdbc.password=1111
    3. - jdbc.driverClass=com.mysql.jdbc.Driver
    4. - jdbc.jdbcUrl=jdbc:mysql:///sms
  • 其他信息配置

    1. initialPoolSize:初始化连接数量
    2. minPoolSize:最小连接数量
    3. maxPoolSize:最大连接数量
    4. acquireIncrement: 当连接池用完之后一次性获取的连接数量
    5. idleConnectionTestPeriod:根据一定的时间间隔检查连接池的连接数量 单位为秒
    6. maxIdleTime:最大空闲时间 单位为秒
    7. maxStatements:最大的maxStatements连接数量
    8. maxStatementsPerConnection:最大语句缓存

db.properties

  1. jdbc.user=root
  2. jdbc.password=1111
  3. jdbc.driverClass=com.mysql.jdbc.Driver
  4. jdbc.jdbcUrl=jdbc:mysql:///sms
  5. jdbc.initPoolSize=5
  6. jdbc.maxPoolSize=10

3、配置XML(已经写注释了,就不多解释了)

  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-4.3.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  7. <!-- 导入资源文件
  8. 读取db.properties文件中的数据 -->
  9. <context:property-placeholder location="classpath:db.properties"/>
  10. <!-- 配置C3P0数据源 -->
  11. <bean id="dataSource"
  12. class="com.mchange.v2.c3p0.ComboPooledDataSource">
  13. <property name="user" value="${jdbc.user}"></property>
  14. <property name="password" value="${jdbc.password}"></property>
  15. <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
  16. <property name="driverClass" value="${jdbc.driverClass}"></property>
  17. <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
  18. <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
  19. </bean>
  20. <!-- 配置Spring的jdbcTemplate
  21. 并注入一个dataSource数据源-->
  22. <bean id="jdbcTemplate"
  23. class="org.springframework.jdbc.core.JdbcTemplate">
  24. <property name="dataSource" ref="dataSource"></property>
  25. </bean>
  26. </beans>

4、测试是否已经连接数据库

  1. package com.linjie.jdbctemplate;
  2. /**
  3. * @author LinJie E-mail:ash-ali@163.com
  4. * @version 创建时间:2018年5月11日 下午4:42:55
  5. * 测试
  6. */
  7. import java.sql.SQLException;
  8. import javax.sql.DataSource;
  9. import org.junit.Test;
  10. import org.springframework.context.ApplicationContext;
  11. import org.springframework.context.support.ClassPathXmlApplicationContext;
  12. import org.springframework.jdbc.core.JdbcTemplate;
  13. public class testJDBC {
  14. private JdbcTemplate jdbcTemplate;
  15. private ApplicationContext context = null;
  16. //初始化连接池
  17. {
  18. context = new ClassPathXmlApplicationContext("applicationContext.xml");
  19. jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
  20. }
  21. //测试是否连接数据库
  22. @Test
  23. public void testIsConnect() throws SQLException {
  24. DataSource dataSource = context.getBean(DataSource.class);
  25. System.out.println("连接成功"+dataSource.getConnection());
  26. }
  27. }

结果(连接成功)

这里写图片描述


七、更新查询操作

既然已经可以连接了,那就进行一些常规操作吧

1、采用的数据库sms,表student

  1. +----+------+----------+--------+------+-------+
  2. | id | num | password | name | age | score |
  3. +----+------+----------+--------+------+-------+
  4. | 1 | 0001 | 111 | pink | 21 | 99 |
  5. | 2 | 11 | 11 | ee | 12 | 55 |
  6. | 3 | 0004 | 123 | linjie | 20 | 99 |
  7. | 4 | 11 | 11 | ww | 11 | 11 |
  8. | 5 | 007 | 123 | pojp | 23 | 99 |
  9. | 6 | 008 | 123 | trtp | 23 | 99 |
  10. | 7 | 009 | 123 | QQQp | 23 | 99 |
  11. | 8 | 007 | 123 | pojp | 23 | 99 |
  12. | 9 | 008 | 123 | trtp | 23 | 99 |
  13. | 10 | 009 | 123 | QQQp | 23 | 99 |
  14. | 11 | 007 | 123 | pojp | 23 | 99 |
  15. | 12 | 008 | 123 | trtp | 23 | 99 |
  16. | 13 | 009 | 123 | QQQp | 23 | 99 |
  17. +----+------+----------+--------+------+-------+

2、update

  1. //修改指定num的name
  2. @Test
  3. public void testUpdate() {
  4. String sql = "update student set name = ? where num = ?";
  5. jdbcTemplate.update(sql, "pink",0001);
  6. System.out.println("success");
  7. }

3、batchUpdate批量更新

  1. /*
  2. *批量更新:批量 insert,update,delete
  3. */
  4. @Test
  5. public void testBatechUpdate() {
  6. String sql = "insert into student(num,password,name,age,score) value(?,?,?,?,?)";
  7. List<Object[]> batchArgs = new ArrayList<Object[]>();
  8. batchArgs.add(new Object[] {"007","123","pojp",23,99});
  9. batchArgs.add(new Object[] {"008","123","trtp",23,99});
  10. batchArgs.add(new Object[] {"009","123","QQQp",23,99});
  11. jdbcTemplate.batchUpdate(sql, batchArgs);
  12. }

4、queryForObject查询单行

查询将查询值返回给对象,创建stu.java
  1. package com.linjie.jdbctemplate;
  2. /**
  3. * @author LinJie E-mail:ash-ali@163.com
  4. * @version 创建时间:2018年5月10日 下午3:34:59
  5. */
  6. public class stu {
  7. private String num;
  8. private String name;
  9. private Integer age;
  10. /**
  11. * @return the num
  12. */
  13. public String getNum() {
  14. return num;
  15. }
  16. /**
  17. * @param num the num to set
  18. */
  19. public void setNum(String num) {
  20. this.num = num;
  21. }
  22. /**
  23. * @return the name
  24. */
  25. public String getName() {
  26. return name;
  27. }
  28. /**
  29. * @param name the name to set
  30. */
  31. public void setName(String name) {
  32. this.name = name;
  33. }
  34. /**
  35. * @return the age
  36. */
  37. public Integer getAge() {
  38. return age;
  39. }
  40. /**
  41. * @param age the age to set
  42. */
  43. public void setAge(Integer age) {
  44. this.age = age;
  45. }
  46. /* (non-Javadoc)
  47. * @see java.lang.Object#toString()
  48. */
  49. @Override
  50. public String toString() {
  51. return "stu [num=" + num + ", name=" + name + ", age=" + age + "]";
  52. }
  53. }
修改初始化连接池代码块
  1. //初始化连接池代码块
  2. {
  3. context = new ClassPathXmlApplicationContext("applicationContext.xml");
  4. jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
  5. studao = (stuDao) context.getBean("stuDao");
  6. }
  7. /*
  8. *从数据库中获取一条记录,实际是得到对应的一个对象
  9. *RowMapper:行的映射
  10. *Spring 2.5 提供了一个便利的RowMapper实现-----BeanPropertyRowMapper
  11. *它可自动将一行数据映射到指定类的实例中 它首先将这个类实例化,然后通过名称匹配的方式,映射到属性中去。
  12. *字段 bean属性
  13. *USER_NAME --> userName
  14. *USER_ID --> userId
  15. */
  16. @Test
  17. public void testQueryForObject() {
  18. String sql = "select num,name,age from student where id = ?";
  19. RowMapper<stu> rowMapper = new BeanPropertyRowMapper<stu>(stu.class);
  20. stu s = jdbcTemplate.queryForObject(sql, rowMapper,5);//最后一个参数为id值
  21. System.out.println(s);
  22. }

5、query查询多行

  1. /*
  2. *查询实体类的集合
  3. */
  4. @Test
  5. public void testQueryForList() {
  6. String sql = "select num,name,age from student where id > ?";
  7. RowMapper<stu> rowMapper = new BeanPropertyRowMapper<stu>(stu.class);
  8. List<stu> s = jdbcTemplate.query(sql, rowMapper,0);//最后一个参数为id值
  9. System.out.println(s);
  10. }

6、queryForObject单值查询

  1. /**
  2. * 获取单个列的值,或统计
  3. */
  4. @Test
  5. public void testQueryObjectqqq() {
  6. String sql = "select count(name) from student";
  7. Long count = jdbcTemplate.queryForObject(sql, Long.class);
  8. System.out.println(count);
  9. }

七、实际应用

stuDao.java(注意:stu类引用上文的)

  1. package com.linjie.jdbctemplate;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.jdbc.core.BeanPropertyRowMapper;
  4. import org.springframework.jdbc.core.JdbcTemplate;
  5. import org.springframework.jdbc.core.RowMapper;
  6. import org.springframework.stereotype.Repository;
  7. /**
  8. * @author LinJie E-mail:ash-ali@163.com
  9. * @version 创建时间:2018年5月10日 下午7:24:51
  10. */
  11. @Repository("stuDao")
  12. public class stuDao {
  13. @Autowired
  14. private JdbcTemplate jdbcTemplate;
  15. public stu get(Integer id) {
  16. String sql = "select num,name,age from student where id = ?";
  17. RowMapper<stu> rowMapper = new BeanPropertyRowMapper(stu.class);
  18. stu s = jdbcTemplate.queryForObject(sql, rowMapper,id);
  19. return s;
  20. }
  21. }

db.properties

  1. jdbc.user=root
  2. jdbc.password=1111
  3. jdbc.driverClass=com.mysql.jdbc.Driver
  4. jdbc.jdbcUrl=jdbc:mysql:///sms
  5. jdbc.initPoolSize=5
  6. jdbc.maxPoolSize=10

applicationContext.xml

  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-4.3.xsd
  6. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  7. <context:component-scan base-package="com.linjie.jdbctemplate"></context:component-scan>
  8. <!-- 导入资源文件
  9. 读取db.properties文件中的数据 -->
  10. <context:property-placeholder location="classpath:db.properties"/>
  11. <!-- 配置C3P0数据源 -->
  12. <bean id="dataSource"
  13. class="com.mchange.v2.c3p0.ComboPooledDataSource">
  14. <property name="user" value="${jdbc.user}"></property>
  15. <property name="password" value="${jdbc.password}"></property>
  16. <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
  17. <property name="driverClass" value="${jdbc.driverClass}"></property>
  18. <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
  19. <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
  20. </bean>
  21. <!-- 配置Spring的jdbcTemplate
  22. 并注入一个dataSource数据源-->
  23. <bean id="jdbcTemplate"
  24. class="org.springframework.jdbc.core.JdbcTemplate">
  25. <property name="dataSource" ref="dataSource"></property>
  26. </bean>
  27. </beans>

test测试类

  1. package com.linjie.jdbctemplate;
  2. /**
  3. * @author LinJie E-mail:ash-ali@163.com
  4. * @version 创建时间:2018年5月10日 上午8:49:38
  5. * 测试
  6. */
  7. import org.junit.Test;
  8. import org.springframework.context.ApplicationContext;
  9. import org.springframework.context.support.ClassPathXmlApplicationContext;
  10. import org.springframework.jdbc.core.JdbcTemplate;
  11. public class JDBCTest {
  12. private ApplicationContext context= null;
  13. private JdbcTemplate jdbcTemplate;
  14. private stuDao studao;
  15. //初始化连接池代码块
  16. {
  17. context = new ClassPathXmlApplicationContext("applicationContext.xml");
  18. jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
  19. studao = (stuDao) context.getBean("stuDao");
  20. }
  21. @Test
  22. public void testsss() {
  23. System.out.println(studao.get(1));
  24. }
  25. }

结果

这里写图片描述


参考

《Spring IN ACTION》
数据库连接池作用及c3p0详解

发表评论

表情:
评论列表 (有 0 条评论,334人围观)

还没有评论,来说两句吧...

相关阅读