Try using Spring JDBC

Purpose

I tried using Spring JDBC from SpringBoot, so I will summarize the procedure for myself.

environment

macOS Sierra 10.12.3 postgres (PostgreSQL) 10.4

DB preparation

Introducing and starting PostgreSQL

$ brew install postgresql
$ postgres -D /usr/local/var/postgres #Start-up

Creating a table

$ createuser -P leonis_sk #User created
Enter password for new role:
Enter it again:
$ createdb db-example -O leonis_sk #create db
$ psql -U leonis_sk db-example #db connection
psql (10.4)
Type "help" for help.

db-example=> create table users (
db-example(> id varchar(20),
db-example(> name varchar(30)
db-example(> );
CREATE TABLE
db-example=> \d
         List of relations
 Schema | Name  | Type  |   Owner
--------+-------+-------+-----------
 public | users | table | leonis_sk
(1 row)

db-example=> select * from users;
 id | name
----+------
(0 rows)

db-example=> insert into users values('A001', 'alex'), ('A002', 'betty'), ('A003', 'carol');
INSERT 0 3
db-example=> select * from users;
  id  | name
------+-------
 A001 | alex
 A002 | betty
 A003 | carol
(3 rows)

db-example=> \q

Creating a Spring Boot Project

Creating a template

https://start.spring.io/ At the above site, you can generate a template of Spring Boot project with the minimum information.

You can download the zip file with Generate Project. Unzip and move to Eclipse workspace. Imported as maven project.

DB connection information

Edit application.properties

src/main/resources/application.properties


spring.datasource.driver-class-name=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/db-example
spring.datasource.username=leonis_sk
spring.datasource.password=password

RestController Create TestController.java like below

java:com.example.demo.TestController.java


package com.example.demo;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(path="/jdbc/sample")
public class TestController {
    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    @RequestMapping(path="/users", method=RequestMethod.GET)
    public String index() {
        List<Map<String,Object>> list;
        list = jdbcTemplate.queryForList("select * from users");
        return list.toString();
    }
    
    @RequestMapping(path="/users/{id}", method=RequestMethod.GET)
    public String read(@PathVariable String id) {
        List<Map<String,Object>> list;
        list = jdbcTemplate.queryForList("select * from users where id = ?", id);
        return list.toString();
    }
}

Run

Start-up

$ pwd
/path/to/eclipse-workspace/demo
$ mvn spring-boot:run

I thought it was time to start, but BUILD SUCCESS came out and stopped.

[INFO] Scanning for projects...
[INFO]
[INFO] --------------------------< com.example:demo >--------------------------
[INFO] Building demo 0.0.1-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] >>> spring-boot-maven-plugin:1.5.13.RELEASE:run (default-cli) > test-compile @ demo >>>
[WARNING] The POM for org.objenesis:objenesis:jar:2.1 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 0 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ demo ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/LEON/eclipse-workspace/demo/src/test/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ demo ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< spring-boot-maven-plugin:1.5.13.RELEASE:run (default-cli) < test-compile @ demo <<<
[INFO]
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.13.RELEASE:run (default-cli) @ demo ---

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.13.RELEASE)

2018-05-14 01:49:38.701  INFO 8906 --- [           main] com.example.demo.DemoApplication         : Starting DemoApplication on LEON-Mac.local with PID 8906 (/Users/LEON/eclipse-workspace/demo/target/classes started by LEON in /Users/LEON/eclipse-workspace/demo)
2018-05-14 01:49:38.707  INFO 8906 --- [           main] com.example.demo.DemoApplication         : No active profile set, falling back to default profiles: default
2018-05-14 01:49:38.795  INFO 8906 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@5901caa1: startup date [Mon May 14 01:49:38 JST 2018]; root of context hierarchy
2018-05-14 01:49:41.108  INFO 8906 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-14 01:49:41.127  INFO 8906 --- [           main] com.example.demo.DemoApplication         : Started DemoApplication in 3.122 seconds (JVM running for 7.238)
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.845 s
[INFO] Finished at: 2018-05-14T01:49:41+09:00
[INFO] ------------------------------------------------------------------------
2018-05-14 01:49:41.132  INFO 8906 --- [       Thread-3] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@5901caa1: startup date [Mon May 14 01:49:38 JST 2018]; root of context hierarchy
2018-05-14 01:49:41.134  INFO 8906 --- [       Thread-3] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown

When I wondered "?", [Similar cases](https://stackoverflow.com/questions/43886815/spring-boot-1-5-3-web-application-terminate-immediately-after-started ? utm_medium = organic & utm_source = google_rich_qa & utm_campaign = google_rich_qa) was also found, but I'm not sure. After trying various things, I changed the parent version of pom.xml from 1.5.13 to 1.5.12 and it worked for some reason.

pom.xml


    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.12.RELEASE</version> <!-- <version>1.5.13.RELEASE</version> --> 
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

I will investigate the cause later, and next.

$ curl http://localhost:8080/jdbc/sample/users
[{id=A001, name=alex}, {id=A002, name=betty}, {id=A003, name=carol}]%
$ curl http://localhost:8080/jdbc/sample/users/A001
[{id=A001, name=alex}]%

When I try to access it with the curl command, it seems that I can get it properly. Even so, Spring Boot is easy.

Recommended Posts

Try using Spring JDBC
Try using Maven
Try using powermock-mockito2-2.0.2
Try using GraalVM
Try using jmockit 1.48
Try using sql-migrate
Try using Spring Boot with VS Code
Try using Axon Framework
Try using JobScheduler's REST-API
Try using java.lang.Math methods
Try using PowerMock's WhiteBox
Spring Data JDBC Preview
Try using Talend Part 1
Try using F # list
Try using each_with_index method
Try using DI container with Laravel and Spring Boot
Try using RocksDB in Java
Try using GloVe with Deeplearning4j
Try using view_component with rails
Try scraping using java [Notes]
Try using Cocoa from Ruby
Try using letter_opener_web for inquiries
[Swift] Try using Collection View
Using Mapper with Java (Spring)
Try using IntelliJ IDEA once
Use Spring JDBC with Spring Boot
Try using gRPC in Ruby
[Rails] Try using Faraday middleware
Try Spring Boot on Mac
[Processing] Try using GT Force.
Try the Spring WebFlux tutorial
[Programming Encyclopedia] ยง2 Try using Ruby
How to use Spring Data JDBC
I tried using Spring + Mybatis + DbUnit
Spring Boot Tutorial Using Spring Security Authentication
Try using Redmine on Mac docker
Implement declarative retry processing using Spring Retry
I tried connecting to MySQL using JDBC Template with Spring MVC
Try manipulating PostgreSQL arrays with JDBC
Part 1: Try using OAuth 2.0 Login supported by Spring Security 5 with Spring Boot
Try using Redis with Java (jar)
Try Spring WebFlux (mainly Router Functions)
[Java] Try to implement using generics
Try using IBM Java method tracing
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
Try using Java framework Nablarch [Web application]
Try using || instead of the ternary operator
Try using the service on Android Oreo
About Spring Dependency Injection using Java, Kotlin
Try using the Rails API (zip code)
Exists using Specification in Spring Data JPA
Study Java Try using Scanner or Map
Try Spring Security AES256 string encryption / decryption
Java and Derby integration using JDBC (using NetBeans)
[Spring] Obfuscate specific fields using annotations [Java]
Try using Reladomo's MT Loader (Multi-Threaded Matcher Loader)
Try Spring Boot 1 (Environment construction ~ Tomcat startup)
Try using JobScheduler's REST-API --Java RestClient implementation--
I tried Spring Data JDBC 1.0.0.BUILD-SNAPSHOT (-> 1.0.0.RELEASE)
Asynchronous processing with Spring Boot using @Async