原文:https://spring.io/guides/gs/relational-data-access/
仍然是一个子模块,父工程的pom https://blog.csdn.net/csdn86868686888/article/details/103758256
4.0.0
com.springboot
springboot-parent
0.0.1-SNAPSHOT
springboot-JDBC
1.8
org.springframework.boot
spring-boot-starter-data-jdbc
com.h2database
h2
runtime
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
工程结构:
代码:
package com.springboot.entity;
public class Customer {
private long id;
private String firstName, lastName;
//省略get,set方法
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);
}
}
package com.springboot;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;
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.core.io.buffer.LimitedDataBufferList;
import org.springframework.jdbc.core.JdbcTemplate;
import com.springboot.entity.Customer;
@SpringBootApplication
public class Application implements CommandLineRunner{
private static final Logger log=LoggerFactory.getLogger(Application.class);
@Autowired
JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) 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))");
List
执行结果是这样的:
主要功能是利用Spring提供的JDBC访问关系型数据库,这里为了演示方便使用的是嵌入内存的关系型数据库h2,插入、查询时候使用了java8以后提供的函数式接口以及Lambda表达式。
代码戳https://github.co/github20131983/springboot