創(chuàng)建一個Customer類
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;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return String.format("Customer[id=%d,firstName='%s',lastName='%s'", id, firstName, lastName);
}
}
存儲和檢索數據
Spring提供了一個名為JdbcTemplate的模板類。
@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);
}
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public void run(String... strings) throws Exception {
log.info("Createing tables");
jdbcTemplate.execute("DROP TABLE customers IF EXISTS ");
jdbcTemplate.execute("CREATE TABLE customers(" +
"id SERIAL, first_name VARCHAR(255), last_name VARCHAR(255))");
List<Object[]> splitUpNames = Arrays.asList("John Woo", "Jeff Dean", "Josh Bloch", "Josh Long").stream()
.map(name -> name.split(" ")).collect(Collectors.toList());
splitUpNames.forEach(name -> log.info(String.format("Inserting customer record for %s %s", name[0], name[1])));
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 Boot支持H2(一種內存中的關系數據庫引擎),并自動創(chuàng)建一個連接。因為我們使用的是spring-jdbc,Spring Boot會自動創(chuàng)建一個JdbcTemplate耕魄。@Autowired JdbcTemplate字段會自動加載它并使其可用。
這個Application類實現了Spring Boot的CommandLineRunner彭谁,這意味著它將在應用程序上下文加載完成后執(zhí)行run()方法吸奴。