packagecom.example.relationaldataaccess;publicclassCustomer{privatelongid;privateStringfirstName,lastName;publicCustomer(longid,StringfirstName,StringlastName){this.id=id;this.firstName=firstName;this.lastName=lastName;}@OverridepublicStringtoString(){returnString.format("Customer[id=%d, firstName='%s', lastName='%s']",id,firstName,lastName);}// getters & setters는 간략화를 위해 생략}
Store and Retrieve Data
Spring은 SQL 관계형 데이터베이스와 JDBC를 사용하기 쉽게 해주는 JdbcTemplate이라는 템플릿 클래스를 제공한다.
JdbcTemplate는 리소스 획득, 연결 관리, 예외 처리 및 코드의 목적과는 전혀 관련이 없는 일반적인 오류 확인 등을 대신 처리해준다.
packagecom.example.relationaldataaccess;importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.boot.CommandLineRunner;importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.jdbc.core.JdbcTemplate;importjava.util.Arrays;importjava.util.List;importjava.util.stream.Collectors;@SpringBootApplicationpublicclassRelationalDataAccessApplicationimplementsCommandLineRunner{privatestaticfinalLoggerlog=LoggerFactory.getLogger(RelationalDataAccessApplication.class);publicstaticvoidmain(Stringargs[]){SpringApplication.run(RelationalDataAccessApplication.class,args);}@AutowiredJdbcTemplatejdbcTemplate;@Overridepublicvoidrun(String...strings)throwsException{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","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 = ?",(rs,rowNum)->newCustomer(rs.getLong("id"),rs.getString("first_name"),rs.getString("last_name")),"Josh").forEach(customer->log.info(customer.toString()));}}
Spring Boot는 H2(인메모리 관계형 데이터베이스 엔진)를 지원하며 자동으로 연결을 생성한다.
현재는 spring-jdbc를 사용하기 때문에, Spring Boot는 자동으로 JdbcTemplate을 생성한다.