[Spring Guides] 通过Spring用JDBC访问关系数据

本指南将引导您了解使用Spring访问关系数据的过程。
你将构建一个使用JdbcTemplate来访问存储在关系数据库中的数据的应用程序

使用Maven构建应用程序
<?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>org.springframework</groupId>
    <artifactId>gs-relational-data-access</artifactId>
    <version>0.1.0</version>

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

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
创建一个Customer对象

您将使用的简单数据访问逻辑管理Customers的名字和姓氏。要在应用程序级别表示此数据需要创建一个Customer类。

package hello;

public class Customer {
    private long id;
    private String firstName, lastName;

    public Customer(long id, String firstName, String lastName) {
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

    // getters & setters omitted for brevity
}
存储和获取数据

Spring提供了一个名为JdbcTemplate的模板类,可以方便地使用SQL关系数据库和JDBC。大多数JDBC代码都涉及资源获取,连接管理,异常处理以及与代码实现完全无关的一般错误检查。JdbcTemplate为你处理这些,你所需要做的是专注于手头上的工作。

package hello;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@SpringBootApplication
public class Application implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String args[]) {
        SpringApplication.run(Application.class, args);
    }

    @Autowired
    JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... strings) throws Exception {

        log.info("Creating tables");

        jdbcTemplate.execute("DROP TABLE customers IF EXISTS");
        jdbcTemplate.execute("CREATE TABLE customers(" +
                "id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");

        // Split up the array of whole names into an array of first/last names
        List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
                .map(name -> name.split(" "))
                .collect(Collectors.toList());

        // Use a Java 8 stream to print out each tuple of the list
        splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));

        // Uses JdbcTemplate's batchUpdate operation to bulk load data
        jdbcTemplate.batchUpdate("INSERT INTO customers(first_name, last_name) VALUES (?,?)", splitUpNames);

        log.info("Querying for customer records where first_name = 'Josh':");
        jdbcTemplate.query(
                "SELECT id, first_name, last_name FROM customers WHERE first_name = ?", new Object[] { "Josh" },
                (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))
        ).forEach(customer -> log.info(customer.toString()));
    }
}
  • main()方法使用Spring Boot的SpringApplication.run()方法启动应用程序。
  • Spring Boot支持H2,一个内存中的关系数据库引擎,并自动创建一个连接。
  • 因为我们使用spring-jdbc,Spring Boot会自动创建一个JdbcTemplate@Autowired JdbcTemplate字段自动加载它并使其可用。

这个Application类实现了Spring Boot的CommandLineRunner,这意味着它将在应用程序上下文被加载之后执行run()方法。

  1. 首先,使用JdbcTemplate的“execute”方法设置一些DDL。
  2. 其次,您将列出一个字符串列表并使用Java 8流,将其分成Java数组中的firstname / lastname对。
    3.然后使用JdbcTemplate的“batchUpdate”方法在新创建的表中设置一些记录。方法调用的第一个参数是查询字符串,最后一个参数(Object s的数组)保存要替换到查询中“?”字符所在位置的变量。

对于单个insert语句,JdbcTemplate的 insert 方法是好的。但是对于多个插入,最好使用batchUpdate。

使用 ?(通过指示JDBC绑定变量来避免SQL注入攻击)来绑定参数。

最后,使用query方法来搜索表中符合条件的记录。再次使用“?”参数创建查询的参数,在进行调用时传递实际值。最后一个参数是Java 8 lambda,用于将每个结果行转换为新的Customer对象。

Java 8 lambdas映射到单一方法接口,如Spring的RowMapper。如果您使用Java 7或更早版本,您可以轻松地插入匿名接口实现,并具有与lambda表达式的正文所包含的方法正文相同的方法体,并且它将与Spring无关。

运行效果如下:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,868评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,313评论 6 342
  • 主要内容 定义Spring的数据访问支持 配置数据库资源 使用Spring提供的JDBC模板 写在前面:经过上一篇...
    程序熊大阅读 9,043评论 1 31
  • 今天下午,忙碌而又清闲的工作,一如既往地做着,心也是一如既往地想着不该想的事情,有点无奈,有点不可思议,可是却不得...
    何小幸运阅读 344评论 0 0
  • 概述 本文是在K8S 1.7.5的基础上,采用不加密的方式安装 Dashboard 1.7.0,安装完成后可以通过...
    生命不惜阅读 676评论 0 0

友情链接更多精彩内容