Accessing Relational Data using
2017-06-11 本文已影响52人
b7cda9616c52
如果不知道如何使用 Spring,请先查看 Building a RESTful Web Service。
官方文章地址:https://spring.io/guides/gs/relational-data-access/
实现示例:使用 JdbcTemplate
访问关系型数据库。
下载地址:
git clone https://github.com/spring-guides/gs-relational-data-access.git
build.gradle 文件:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
jar {
baseName = 'gs-relational-data-access'
version = '0.1.0'
}
repositories {
mavenCentral()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
dependencies {
compile("org.springframework.boot:spring-boot-starter")
compile("org.springframework:spring-jdbc")
compile("com.h2database:h2")
testCompile("junit:junit")
}
创建 src/main/java/hello/Customer.java
,里面包括 id,firstName、lastName:
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
}
src/main/java/hello/Application.java
:
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()));
}
}
Spring 支持 H2,一个在内存中实现关系型数据库的库,并且自动创建连接。使用 spring-jdbc,Spring Boot 会自动创建 JdbcTemplate
,@Autowired JdbcTemplate
自动加载 JdbcTemplate
并使其可用。
Application
实现了 CommandLineRunner
,应用启动好后会自动执行 run()
方法。
使用 JdbcTemplate’s
execute` 执行 DDL(数据库定义语言)。
想数据库中插入许多数据使用 JdbcTemplate.batchUpdate
,插入一条数据使用 JdbcTemplate.insert
。
使用 ?
可防止 SQL injection attacks(SQL 注入攻击)。
执行结果如下:
2017-06-11 17:07:33.909 INFO 7139 --- [ main] hello.Application : Creating tables
2017-06-11 17:07:33.952 INFO 7139 --- [ main] hello.Application : Inserting customer record for John Woo
2017-06-11 17:07:33.952 INFO 7139 --- [ main] hello.Application : Inserting customer record for Jeff Dean
2017-06-11 17:07:33.952 INFO 7139 --- [ main] hello.Application : Inserting customer record for Josh Bloch
2017-06-11 17:07:33.952 INFO 7139 --- [ main] hello.Application : Inserting customer record for Josh Long
2017-06-11 17:07:33.985 INFO 7139 --- [ main] hello.Application : Querying for customer records where first_name = 'Josh':
2017-06-11 17:07:33.992 INFO 7139 --- [ main] hello.Application : Customer[id=3, firstName='Josh', lastName='Bloch']
2017-06-11 17:07:33.992 INFO 7139 --- [ main] hello.Application : Customer[id=4, firstName='Josh', lastName='Long']