Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Spring Boot
Java Do #10

ueno-haruki
• & 15 

• SpringBoot 

• 10 

• SpringBoot 

•
https://goo.gl/upBqAE
URL
• Spring Boot
• RDB SQL
• Spring Boot Spring JDBC
DB
Spring
Java
WEB
Spring
Spring
…
Spring Boot
Spring boot
SpringBoot
RDB and SQL
RDB
SQL
RDB
SQL
SQL
INSERT INTO VALUES ( )
SELECT FROM WHERE
INESRT INTO customers(first_name, last_name) VALUES ( ‘John’, ‘Woo’)
SELECT fir...
Today’s Main Contents ! JDBC with Spring
RDB(PostgreSQL, MySQL, Oracle, etc…)
Spring
…
Java RDB
JDBC Driver
RDB
Spring JDBC <—
Mybatis
Sql2o
etc…
JDBC Driver
import java.sql.*;
class DBAccess {
public static void main (String args[])
throws SQLException, ClassNotFound...
Accessing Relational Data using JDBC with Spring
JdbcTemplate
RDB
SQL
RDB
SQL
SpringBoot
Spring JDBC
H2 (Database)
pom.xml
<parent>
<!-- spring-boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</...
pom.xml
src/test/java/jp/javado/springboot/AppTest.java
pom.xml mvn
springboot-jdbc
$ mvn
$ mvn compile
[INFO] BUILD SUCCE...
DB
DB
src/main/java/jp/javado/springboot
Customer.java
package jp.javado.springboot;
public class Customer {
private long ...
SpringBoot
SpringBoot
@SpringBootApplication
SpringBoot
@EnableAutoConfiguration, @ComponentScan Spring Annotation
CommandL...
@SpringBootApplication
public class App implements CommandLineRunner {
private static final Logger log = LoggerFactory.get...
package jp.javado.springboot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.fa...
7
RDB
run()
DROP TABLE customers IF EXSITS
customers
• id SERIAL <-
• first_name VARCHAR(255)
• last_name VARCHAR(255)
H2 RDB...
SpringBoot
. ____ _ __ _ _
/ / ___'_ __ _ _(_)_ __ __ _    
( ( )___ | '_ | '_| | '_ / _` |    
/ ___)| |_)| | | | | || (_...
List<Object[]> insertDataList = new ArrayList<>();
insertDataList.add(new Object[]{ "John", "Woo"});
insertDataList.add(ne...
log.info("Querying for customer records where first_name = 'Josh':");
String selectSql = "SELECT id, first_name, last_name...
SpringBoot
• SpringBoot DB
• DB
•
•
•
$ mvn spring-boot:run
DB
INFO 19776 --- [ main] jp.javado.springboot.App : Customer[...
DB
Customer
BeanPropertyRowMapper
Customer
DB
BeanPropertyRowMapper<>(“ ”)
import
BeanPropertyRowMapper
Customer setter,getter,
import org.springframework.jdbc.core....
package jp.javado.springboot;
public class Customer {
private long id;
private String firstName, lastName;
public Customer...
DB
$ mvn spring-boot:run
INFO 19954 --- [ main] jp.javado.springboot.App : Customer[id=3, firstName='Josh', lastName='Long...
DB
DB
JavaDo #10
Spring Boot
ueno-haruki
“Thank you.”
Spring boot入門ハンズオン第二回
Upcoming SlideShare
Loading in …5
×

Spring boot入門ハンズオン第二回

167 views

Published on

SpringBootでJDBCを扱うための入門
「Accessing Relational Data using JDBC with Spring」をベースに一部噛み砕きながら解説していきます。

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Spring boot入門ハンズオン第二回

  1. 1. Spring Boot Java Do #10 ueno-haruki
  2. 2. • & 15 • SpringBoot • 10 • SpringBoot • https://goo.gl/upBqAE URL
  3. 3. • Spring Boot • RDB SQL • Spring Boot Spring JDBC DB
  4. 4. Spring Java WEB Spring
  5. 5. Spring …
  6. 6. Spring Boot Spring boot SpringBoot
  7. 7. RDB and SQL RDB SQL RDB SQL
  8. 8. SQL INSERT INTO VALUES ( ) SELECT FROM WHERE INESRT INTO customers(first_name, last_name) VALUES ( ‘John’, ‘Woo’) SELECT first_name FROM customers WHERE last_name = ‘Woo’ customers first_name John last_name Woo last_name Woo John
  9. 9. Today’s Main Contents ! JDBC with Spring RDB(PostgreSQL, MySQL, Oracle, etc…) Spring
  10. 10. … Java RDB JDBC Driver RDB Spring JDBC <— Mybatis Sql2o etc…
  11. 11. JDBC Driver import java.sql.*; class DBAccess { public static void main (String args[]) throws SQLException, ClassNotFoundException { Class.forName(“org.postgresql.Driver"); try ( Connection conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/testdb", "test", “pass”) ) { try (PreparedStatement stmt = conn.prepareStatement() ) { try ( ResultSet rset = stmt.executeQuery("select first_name, last_name from customer”) ) { while ( rset.next() ) { System.out.println(rset.getInt(1) + "t" + rset.getString(2)); } } catch(Exception eee) { } } catch(Exception ee) { } catch(Exception e) { } } } Driver JDBC
  12. 12. Accessing Relational Data using JDBC with Spring JdbcTemplate RDB SQL
  13. 13. RDB SQL SpringBoot Spring JDBC H2 (Database)
  14. 14. pom.xml <parent> <!-- spring-boot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <!-- springboot jdbc --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <!-- H2(RDB) --> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <!-- maven springboot --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> spring-boot jdbc RDB H2 pom.xml junit <url>http://maven.apache.org</url> </project> juni <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> https://goo.gl/9daFPw URL
  15. 15. pom.xml src/test/java/jp/javado/springboot/AppTest.java pom.xml mvn springboot-jdbc $ mvn $ mvn compile [INFO] BUILD SUCCESS OK spring-boot h2 jar
  16. 16. DB DB src/main/java/jp/javado/springboot Customer.java package jp.javado.springboot; 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); } }
  17. 17. SpringBoot SpringBoot @SpringBootApplication SpringBoot @EnableAutoConfiguration, @ComponentScan Spring Annotation CommandLineRunner JdbcTemplate Spring RDB JdbcTemplate JdbcTemplate RDB Spring @Autowired @Autowired Spring DI RDB Spring DI
  18. 18. @SpringBootApplication public class App implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(App.class); public static void main(String args[]) { SpringApplication.run(App.class, args); } @Autowired JdbcTemplate jdbcTemplate; @Override public void run(String... strings) throws Exception { } } SpringBoot SpringBoot RDB JdbcTemplate JdbcTemplate SpringBoot DB JdbcTemplate
  19. 19. package jp.javado.springboot; 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; @SpringBootApplication public class App implements CommandLineRunner { private static final Logger log = LoggerFactory.getLogger(App.class); public static void main(String args[]) { SpringApplication.run(App.class, args); } @Autowired JdbcTemplate jdbcTemplate; @Override public void run(String... strings) throws Exception { } } src/main/java/jp/javado/springboot/App.java
  20. 20. 7
  21. 21. RDB run() DROP TABLE customers IF EXSITS customers • id SERIAL <- • first_name VARCHAR(255) • last_name VARCHAR(255) H2 RDB 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))");
  22. 22. SpringBoot . ____ _ __ _ _ / / ___'_ __ _ _(_)_ __ __ _ ( ( )___ | '_ | '_| | '_ / _` | / ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |___, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.6.RELEASE) 2017-09-01 22:57:16.511 INFO 21044 --- [ main] jp.javado.springboot.App : Starting App on uenoharutakeshi-no-MacBook-Pro.local with PID 21044 (/Users/haruki/javado/maven/20170903/springboot/springboot-jdbc/target/classes started by haruki in /Users/haruki/javado/maven/20170903/springboot/springboot-jdbc) 2017-09-01 22:57:16.515 INFO 21044 --- [ main] jp.javado.springboot.App : No active profile set, falling back to default profiles: default 2017-09-01 22:57:16.595 INFO 21044 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@13bf19f7: startup date [Fri Sep 01 22:57:16 JST 2017]; root of context hierarchy 2017-09-01 22:57:17.731 INFO 21044 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2017-09-01 22:57:17.745 INFO 21044 --- [ main] jp.javado.springboot.App : Creating tables 2017-09-01 22:57:18.047 INFO 21044 --- [ main] jp.javado.springboot.App : Started App in 2.011 seconds (JVM running for 5.476) [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ SpringBoot SpringBoot $ mvn spring-boot:run
  23. 23. List<Object[]> insertDataList = new ArrayList<>(); insertDataList.add(new Object[]{ "John", "Woo"}); insertDataList.add(new Object[]{ "John", "Titor"}); insertDataList.add(new Object[]{ "Josh", "Long"}); String insertSql = "INSERT INTO customers(first_name, last_name) VALUES (?,?)"; for (Object[] insertData : insertDataList) { jdbcTemplate.update(insertSql, insertData); } INSERT DB jdbcTemplate.update()
  24. 24. log.info("Querying for customer records where first_name = 'Josh':"); String selectSql = "SELECT id, first_name, last_name FROM customers WHERE first_name = ?"; List<Customer> customerList = jdbcTemplate.query(selectSql, new Object[] { "Josh" }, (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString("last_name"))); // SQL customerList.stream().forEach(customer -> log.info(customer.toString())); RDB SELECT , jdbcTemplate.query() query( "SQL " , "SQL ", "SQL ") "SQL " DB rs.getString() Customer DB SELECT
  25. 25. SpringBoot • SpringBoot DB • DB • • • $ mvn spring-boot:run DB INFO 19776 --- [ main] jp.javado.springboot.App : Customer[id=3, firstName='Josh', lastName='Long']
  26. 26. DB Customer BeanPropertyRowMapper Customer
  27. 27. DB BeanPropertyRowMapper<>(“ ”) import BeanPropertyRowMapper Customer setter,getter, import org.springframework.jdbc.core.BeanPropertyRowMapper; List<Customer> customerList = jdbcTemplate.query(selectSql, new Object[] { "Josh" }, (rs, rowNum) -> new Customer(rs.getLong("id"), rs.getString("first_name"), rs.getString(“last_name”))); List<Customer> customerList = jdbcTemplate.query(selectSql, new Object[] { "Josh" }, new BeanPropertyRowMapper<>(Customer.class) );
  28. 28. package jp.javado.springboot; public class Customer { private long id; private String firstName, lastName; public Customer() { } 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); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
  29. 29. DB $ mvn spring-boot:run INFO 19954 --- [ main] jp.javado.springboot.App : Customer[id=3, firstName='Josh', lastName='Long']
  30. 30. DB DB
  31. 31. JavaDo #10 Spring Boot ueno-haruki “Thank you.”

×