本文主要讲这用JDBCTemplate的模板类去操作数据库,同时涉及到JAVA8的新功能用法,大家可以学习。
程序结构
└── src
└── main
└── java
└── hello
pom.xml文件
<?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 https://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>2.1.6.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-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>
Spring Boot将会你做如下的事:
- 将 classpath 里面所有用到的jar包构建成一个可执行的 JAR 文件,方便执行你的程序
- 搜索public static void main()方法并且将它当作可执行类
- 根据springboot版本,去查找相应的依赖类版本,当然你可以定义其它版本。
获取一个Customer对像
创建一个客户类,保存id,名字
src/main/java/hello/Customer.java
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为您处理所有这些问题。你所要做的就是集中精力完成手头的任务。
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()));
}
}
@SpringBootApplication包含如下注解:
- @Configuration 将类标记为应用程序上下文的bean定义源。
- @EnableAutoConfiguration 告诉SpringBoot根据类路径设置、其他bean和各种属性设置开始添加bean。
- @ComponentScan 告诉Spring在hello包中查找其他组件、配置和服务。
您注意到没有一行XML吗?也没有web.xml文件。这个Web应用程序是100%纯Java,您不必麻烦的基础配置。
SpringBoot支持内存中的关系数据库引擎H2,并自动创建连接。因为我们使用的是SpringJDBC,所以SpringBoot会自动创建一个JDBCTemplate。@Autowired JdbcTemplate字段自动加载并使其可用。
这个应用程序类实现了Spring boot的CommandLineRunner ,这意味着它将在加载应用程序上下文后执行run()方法。
- 首先,使用 JdbcTemplate的execute方法安装一些DDL。
- 其次,使用字符串列表并使用Java 8流,将它们拆分为Java数组中的firstname/lastname对
- 然后使用JdbcTemplate的batchUpdate方法在新创建的表中插入一些记录。对于单个insert语句,JdbcTemplate的insert方法是好的。但是对于多个插入,最好使用batchUpdate。
使用?通过指示JDBC绑定变量来避免SQL注入攻击的参数。
最后,使用查询方法在表中搜索符合条件的记录。你又用了?参数,作为查询创建参数,在调用时传入实际值。最后一个参数是Java 8 lambda,用于将每个结果行转换为新的客户对象。
Java 8 lambdas很好地映射到单个方法接口上,比如Spring的RowMapper。如果您使用的是Java 7或更早的版本,您可以很容易地插入匿名接口实现,并具有与lambda Express的正文包含的相同方法体,并且它不会在Spring中工作。
运行你的程序(STS下,Maven可参考前面文章):
右键-选择Run as-Spring Boot App ,输出如下:
2015-06-19 10:58:31.152 INFO 67731 --- [ main] hello.Application : Creating tables
2015-06-19 10:58:31.219 INFO 67731 --- [ main] hello.Application : Inserting customer record for John Woo
2015-06-19 10:58:31.220 INFO 67731 --- [ main] hello.Application : Inserting customer record for Jeff Dean
2015-06-19 10:58:31.220 INFO 67731 --- [ main] hello.Application : Inserting customer record for Josh Bloch
2015-06-19 10:58:31.220 INFO 67731 --- [ main] hello.Application : Inserting customer record for Josh Long
2015-06-19 10:58:31.230 INFO 67731 --- [ main] hello.Application : Querying for customer records where first_name = 'Josh':
2015-06-19 10:58:31.242 INFO 67731 --- [ main] hello.Application : Customer[id=3, firstName='Josh', lastName='Bloch']
2015-06-19 10:58:31.242 INFO 67731 --- [ main] hello.Application : Customer[id=4, firstName='Josh', lastName='Long']
2015-06-19 10:58:31.244 INFO 67731 --- [ main] hello.Application : Started Application in 1.693 seconds (JVM running for 2.054)
我用业余时间翻译了spring.io官方,网站上的例子,放在我个人网站上,希望对大家有帮助