• Spring系列文章:Spring使用JdbcTemplate


    一、简介

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

    第一步:引入依赖

    1. <dependency>
    2. <groupId>org.springframeworkgroupId>
    3. <artifactId>spring-contextartifactId>
    4. <version>6.0.2version>
    5. dependency>
    6. <dependency>
    7. <groupId>junitgroupId>
    8. <artifactId>junitartifactId>
    9. <version>4.13.2version>
    10. <scope>testscope>
    11. dependency>
    12. <dependency>
    13. <groupId>mysqlgroupId>
    14. <artifactId>mysql-connector-javaartifactId>
    15. <version>8.0.30version>
    16. dependency>
    17. <dependency>
    18. <groupId>org.springframeworkgroupId>
    19. <artifactId>spring-jdbcartifactId>
    20. <version>6.0.2version>
    21. 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等。我们这⾥⾃⼰先⼿写⼀个数据源。

    1. public class MyDataSource implements DataSource {
    2. // 添加4个属性
    3. private String driver;
    4. private String url;
    5. private String username;
    6. private String password;
    7. // 提供4个setter⽅法
    8. public void setDriver(String driver) {
    9. this.driver = driver;
    10. }
    11. public void setUrl(String url) {
    12. this.url = url;
    13. }
    14. public void setUsername(String username) {
    15. this.username = username;
    16. }
    17. public void setPassword(String password) {
    18. this.password = password;
    19. }
    20. // 重点写怎么获取Connection对象就⾏。其他⽅法不⽤管。
    21. @Override
    22. public Connection getConnection() throws SQLException {
    23. try {
    24. Class.forName(driver);
    25. Connection conn = DriverManager.getConnection(url, username, password);
    26. return conn;
    27. } catch (Exception e) {
    28. e.printStackTrace();
    29. }
    30. return null;
    31. }
    32. @Override
    33. public Connection getConnection(String username, String password) throws SQLException {
    34. return null;
    35. }
    36. @Override
    37. public PrintWriter getLogWriter() throws SQLException {
    38. return null;
    39. }
    40. @Override
    41. public void setLogWriter(PrintWriter out) throws SQLException {
    42. }
    43. @Override
    44. public void setLoginTimeout(int seconds) throws SQLException {
    45. }
    46. @Override
    47. public int getLoginTimeout() throws SQLException {
    48. return 0;
    49. }
    50. @Override
    51. public Logger getParentLogger() throws SQLFeatureNotSupportedException {
    52. return null;
    53. }
    54. @Override
    55. public T unwrap(Class iface) throws SQLException {
    56. return null;
    57. }
    58. @Override
    59. public boolean isWrapperFor(Class iface) throws SQLException {
    60. return false;
    61. }
    62. }

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

    1. "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
    6. http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    8. <bean id="myDataSource" class="com.springcode.example.entity.MyDataSource">
    9. <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
    10. <property name="url" value="jdbc:mysql://localhost:3306/spring6"/>
    11. <property name="username" value="root"/>
    12. <property name="password" value="root"/>
    13. bean>
    14. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    15. <property name="dataSource" ref="myDataSource"/>
    16. bean>
    17. beans>

    三、增删改查

    1、增加

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

    2、修改

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

    3、删除

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. // 执⾏delete
    7. String sql = "delete from t_user where id = ?";
    8. int count = jdbcTemplate.update(sql, 1);
    9. System.out.println("删除了⼏条记录:" + count);
    10. }
    11. }

    4、查询一个对象

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

    5、查询多个对象

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. // 执⾏select
    7. String sql = "select id, real_name, age from t_user";
    8. List users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
    9. System.out.println(users);
    10. }
    11. }

    6、查询⼀个值

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. // 执⾏select
    7. String sql = "select count(1) from t_user";
    8. Integer count = jdbcTemplate.queryForObject(sql, int.class); // 这⾥⽤Integer.class也可以
    9. System.out.println("总记录条数:" + count);
    10. }
    11. }

    7、批量添加

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. // 批量添加
    7. String sql = "insert into t_user(id,real_name,age) values(?,?,?)";
    8. Object[] objs1 = {null, "⼩花", 20};
    9. Object[] objs2 = {null, "⼩明", 21};
    10. Object[] objs3 = {null, "⼩刚", 22};
    11. List list = new ArrayList<>();
    12. list.add(objs1);
    13. list.add(objs2);
    14. list.add(objs3);
    15. int[] count = jdbcTemplate.batchUpdate(sql, list);
    16. System.out.println(Arrays.toString(count));
    17. }
    18. }

    8、批量修改

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

    9、批量删除

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. // 批量删除
    7. String sql = "delete from t_user where id = ?";
    8. Object[] objs1 = {2};
    9. Object[] objs2 = {3};
    10. Object[] objs3 = {4};
    11. List list = new ArrayList<>();
    12. list.add(objs1);
    13. list.add(objs2);
    14. list.add(objs3);
    15. int[] count = jdbcTemplate.batchUpdate(sql, list);
    16. System.out.println(Arrays.toString(count));
    17. }
    18. }

    10、使⽤回调函数

    1. public class SpringTest {
    2. @Test
    3. public void test(){
    4. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
    5. JdbcTemplate jdbcTemplate = applicationContext.getBean("jdbcTemplate", JdbcTemplate.class);
    6. String sql = "select id, real_name, age from t_user where id = ?";
    7. User user = jdbcTemplate.execute(sql, new PreparedStatementCallback() {
    8. @Override
    9. public User doInPreparedStatement(PreparedStatement ps) throws SQLException, DataAccessException {
    10. User user = null;
    11. ps.setInt(1, 5);
    12. ResultSet rs = ps.executeQuery();
    13. if (rs.next()) {
    14. user = new User();
    15. user.setId(rs.getInt("id"));
    16. user.setRealName(rs.getString("real_name"));
    17. user.setAge(rs.getInt("age"));
    18. }
    19. return user;
    20. }
    21. });
    22. System.out.println(user);
    23. }
    24. }

    四、使⽤德鲁伊连接池

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

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

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>druidartifactId>
    4. <version>1.1.8version>
    5. dependency>

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

    1. "1.0" encoding="UTF-8"?>
    2. "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
    6. http://www.springframework.org/schema/beans/spring-beans.xsd
    7. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    8. "druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
    9. "driverClassName" value="com.mysql.cj.jdbc.Driver"/>
    10. "url" value="jdbc:mysql://localhost:3306/spring6"/>
    11. "username" value="root"/>
    12. "password" value="root"/>
    13. "jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    14. "dataSource" ref="druidDataSource"/>

    测试

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

  • 相关阅读:
    第二章:人工智能深度学习教程-深度学习简介
    matlab图像类型的转换九种
    Angular-03:组件模板
    qt程序的CMakeLists.txt配置转为平台的qt的.pro项目工程文件
    ElasticSearch万字入门教程 一天上手ElasticSearch
    Spring cloud gateway过滤器学习
    【JavaScript原型链prototype详解】
    CSS属性 - box-sizing
    蓝桥杯物联网_STM32L071_1_CubMx&keil5基础配置
    c语言入门---调试技巧
  • 原文地址:https://blog.csdn.net/qq_34491508/article/details/132754277