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

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

使用Maven构建应用程序


    4.0.0

    org.springframework
    gs-relational-data-access
    0.1.0

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.7.RELEASE
    

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
            com.h2database
            h2
        
    


    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


创建一个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 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无关。

运行效果如下:

[Spring Guides] 通过Spring用JDBC访问关系数据_第1张图片

你可能感兴趣的:([Spring Guides] 通过Spring用JDBC访问关系数据)