SpringBoot——使用Spring和JDBC访问关系型数据
2018-04-05 本文已影响0人
打铁大师
创建一个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(一种内存中的关系数据库引擎),并自动创建一个连接。因为我们使用的是spring-jdbc,Spring Boot会自动创建一个JdbcTemplate。@Autowired JdbcTemplate字段会自动加载它并使其可用。
这个Application类实现了Spring Boot的CommandLineRunner,这意味着它将在应用程序上下文加载完成后执行run()方法。