본문 바로가기
Server/Spring Boot

SpringBoot #4 Spring boot - JDBC - MySQL

by HaningYa 2020. 4. 30.
728x90

  • Spring boot 에서 JDBC로 MySQL 쿼리 날리기

 

1. Local MySQL Server 켠다.

2. Spring boot 프로젝트의 application.properties에서 configure에 필요한 설정한다.

server.port = 8080
spring.datasource.url=jdbc:mysql://localhost:3306/(디비이름)
spring.datasource.username=root
spring.datasource.password=(비밀번호)
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.ㅁgenerate-ddl=true
spring.jpa.hibernate.ddl-auto = update

3.  JDBC template 을 사용하는데 데이터 소스를 설정한다.

 @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setDataSource(DataSource dataSource){
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

4. 쿼리 날려본다.

package com.example.dbmasterspringboot;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class jdbcController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    public void setDataSource(DataSource dataSource){
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    @RequestMapping(value = "/test")
    public List<Map<String, Object>> test(){
        String tableName = "masterdb";
        List<Map<String, Object>> data = new ArrayList<>();
        data = jdbcTemplate.queryForList("SELECT * FROM "+tableName);

        return data;
    }


}

5. 에러난다.

더보기

There was an unexpected error (type=Internal Server Error, status=500).

Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: The server time zone value 'KST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone' configuration property) to use a more specifc time zone value if you want to utilize time zone support.

 

application.properties 에서 서버 타임존 관련 정보를 추가한다.

spring.datasource.url=jdbc:mysql://localhost:3306/masterdb?serverTimezone=UTC&useSSL=true

6. 예시 디비에 데이터 넣어보고 테스트 해본다.

테이블2개
사용할 테이블
insert

 

조회된다.


 

728x90

댓글