Accessing Relational Data using JDBC with Spring
您将使用Spring JdbcTemplate 构建应用,
访问数据库中数据
。
下面的简单数据访问逻辑,将与下面的管理客户的姓氏和名字。 表示该数据在应用程序级别,创建一个
客户
类。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 很好实现,
你所要做的就是专注于手头的任务。
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()));
}
}
@SpringBootApplication包括 @Configuration @EnableAutoConfiguration
@ComponentScan
SpringApplication.run()用来启动容器应用
spring boot spots H2 ,一个内存中的关系数据库引擎,并自动创建一个连接。 因为我们使用的是 spring jdbc,
spring的自动创建一个
JdbcTemplate
。 用 @ autowired JdbcTemplate 注解
自动加载它,使其可用。
这Application
类实现spring boot中的 CommandLineRunner
,这意味着它将执行 run()
方法在应用程序加载启动的时候。对于单一的insert语句, JdbcTemplate的插入 方法是好的。 但对于多个插入,最好使用batchUpdate 。 |
使用 ? 对于参数避免 SQL注入攻击 指示JDBC绑定变量。 |
使用maven构建项目,下面是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.2.5.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-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>
The
Spring Boot Maven plugin
提供很多方便的特性
-
它集成的所有jar文件的类路径中,构建一个单一的、可运行的“uber-jar”,这使得它更方便执行和提供服务。
它搜索 public static
void main()
标志作为一个可运行的类方法。它提供了一个内置的依赖项解析器,设置版本号相匹配 spring boot依赖性,你可以重写。