在Spring中使用JDBC访问关系数据

你需要什么

  • 大约15分钟
  • IntelliJ IDEA或其他编辑器
  • JDK 1.8或更高版本
  • Maven 3.2+

你会建立什么

您将使用Spring的 JdbcTemplate 构建一个应用程序来访问存储在关系数据库中的数据。

构建步骤

1、添加maven依赖。

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- Spring Boot支持H2(一种内存中的关系数据库引擎),并自动创建一个连接。 -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

2、新建POJO

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
}

3、建表、存数据以及取数据。


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(" ")) //将List中的字符串变成字符数组
                .collect(Collectors.toList()); //将流对象转化为List

        // 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()));
    }
}
  • 这个Application类实现了Spring Boot的CommandLineRunner,这意味着它将在应用程序上下文加载后执行run()方法。
  • 你可以使用JdbcTemplate的execute方法来执行一些DDL。
  • 对于单插入语句,JdbcTemplate的insert方法很好。但对于多个插入,最好使用batchUpdate
  • 使用 通过指示JDBC绑定变量来避免SQL注入攻击的参数。

测试

集成完后直接运行main()方法就可以运行Spring程序。执行结果如下:

原文地址 https://spring.io/guides/gs/relational-data-access/

猜你喜欢

转载自blog.csdn.net/she_lock/article/details/80569189