SpringBoot使用JdbcTemplate

  JdbcTemplate的设计目的是为不同类型的HJDBC操作提供模板方法,每个模板方法都能控制整个数据访问的过程。

常用方法:

  1. execute:可以用于执行任何的SQL语句,一般用于执行DDL语句;
  2. update和batchUpdate:用于执行新增、修改、删除等语句,batch是批量的意思;
  3. query和queryForObject:用于查询相关语句;
  4. call:用于执行存储过程、函数等语句。

JdbcTemplate对应的配置信息如下:

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

完整的pom配置如下:

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.cjs</groupId>
  <artifactId>springjdbctemplatetest</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>springjdbctemplatetest</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.6.RELEASE</version>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

<!-- Web依赖 -->
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

<!-- Mysql依赖 -->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>

<!-- JDBC依赖 -->
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-jdbc -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

省略application.properties和Bean类的创建,直接给出XXXDaoImpl类,

package com.cjs.dao.impl;

import com.cjs.bean.User;
import com.cjs.dao.UserDao;
import com.mysql.jdbc.Statement;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Resource
    private JdbcTemplate jdbcTemplate;//注入Jdbc模板核心对象

    @Override
    public int insertUser() {
        String sql = "insert into tb_users(loginname, username, password)"
                    + " values(?,?,?),(?,?,?),(?,?,?)";
        Object[] args = new Object[]{"swk","Tom", "123456","zbj", "Jean","123456","ts","Jimmy","123456"};
        return jdbcTemplate.update(sql, args);//update(String sql, Object[] obj{}),第一个参数时sql语句,第二个参数是填充sql语句的?参数,依次填入
    }

    @Override
    public User selectByUserName(String username) {
        String sql = "select * from tb_users where username = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);//设置返回数据类型
        User user = jdbcTemplate.queryForObject(sql, new Object[]{username}, rowMapper);
        return user;
    }

    @Override
    public User selectUserById(int id) {
        String sql = "select * from tb_users where id = ?";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        User user = jdbcTemplate.queryForObject(sql, new Object[]{id}, rowMapper);
        return user;
    }

    @Override
    public List<User> findAll() {
        String sql = "select * from tb_users";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        return jdbcTemplate.query(sql, rowMapper);
    }

    @Override
    public void delete(Integer id) {
        String sql = "delete from tb_users where id=?";
        jdbcTemplate.update(sql, new Object[]{id});
    }

    @Override
    public void update(User user) {
        String sql = "update tb_users set username=?, loginname=? where id=?";
        jdbcTemplate.update(sql, new Object[]{user.getUsername(), user.getLoginname(), user.getId()});
    }

    @Override
    public User insertGetKey(final User user) {//获取新插入数据的id
        KeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                String sql = "insert into tb_users(username, loginname, password) values(?,?,?)";
                PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                ps.setString(1,user.getUsername());
                ps.setString(2,user.getLoginname());
                ps.setString(3,user.getPassword());
                return ps;
            }
        }, holder);

        int newUserId = holder.getKey().intValue();
        user.setId(newUserId);
        return user;
    }
}

Biz层和Controller也不是这里重点,上面已经将JdbcTemplate的使用说清楚了,因为文中所说那几个常用的方法有很多重载,有些人喜欢用三个参数的,xxx(String sql, Object[] obj, RowMapper<T> rm);不管需不需要填充sql语句参数,都写上,看个人习惯而已。

posted @ 2018-10-29 22:11  KamShing  阅读(1119)  评论(0编辑  收藏  举报