1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
public class SpringDemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringDemoApplication.class, args);
}
// 创建日志
private static final Logger log = LoggerFactory.getLogger(SpringDemoApplication.class);
// 初始化JdbcTemplate 会自动连接h2database数据库
@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))");
// 输入数据
List<Object[]> splitUpNames = Arrays.asList("John Woo","Jeff Dean", "Josn Bokch", "Josh Long").stream()
.map(name -> name.split(" ")).collect(Collectors.toList());
splitUpNames.forEach(name -> log.info(String.format("Inserting customers record for %s %s", name[0], name[1])));
jdbcTemplate.batchUpdate("INSERT INTO customers (first_name, last_name) VALUES (?, ?)", splitUpNames);
// 查询数据
log.info("Querying for customers records where first_name = 'Josh");
jdbcTemplate.query(
"SELECT id, first_name, last_name FROM customers WHERE first_name = ?",
new Object[] {"Josh"},
(rs, column) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name")))
.forEach(customer -> log.info(customer.toString()));
}
}
|