Chillax in dev

[SpringBoot] 스프링 부트 Oracle DB 연동하는법 본문

Java 공부/Spring Boot

[SpringBoot] 스프링 부트 Oracle DB 연동하는법

Seong Story 2020. 10. 21. 11:45
728x90

[SpringBoot] 스프링 부트의 application.properties로 Oracle DB 연동하는 법

- 스프링 부트를 공부하면서 모바일에 좀 더 유익함을 제공해주는 빌드 툴인 Gradel프로젝트로 간단한 sql문을 select 하는 예제를 실습하다 발생한 문제를 해결하는 과정을 포스팅합니다.

 

- 이클립스와 oracle DB를 통해 실험할 예정이며 프로젝트 생성부터 연동후 실행까지의 과정을 정리했습니다.

- 특히 ojdbc.jar 파일이 없어 발생한 오류와 그 해결 과정도 다루었습니다.

 

1. 프로젝트 생성

방법 : 차근차근 아래 순서대로 해주세요.

(1) file > new > spring starter projrct 선택

1

(2) 프로젝트명, 패키지 사용언어나 버전 등을 알맞게 설정합니다.

2

(3) 여기선 pom.xml처럼 필요한 기능을 체크해주기만 하면 알아서 세팅을 해준답니다. JDBC API, Lombok, spring web을 선택하여 생성을 종료합니다.

3

(4) 이제 build.gradle을 설정해줍니다. 내서 체크해준 녀석들이 잘 들어왔나 볼 수 있고 jsp에 사용할 jstl, jasper 등을 준비해줍니다.

// <추가할 부분>
implementation 'javax.servlet:jstl' //jstl
implementation 'org.apache.tomcat.embed:tomcat-embed-jasper' //jsp
// <전체 코드>
plugins {
	id 'org.springframework.boot' version '2.3.4.RELEASE'
	id 'io.spring.dependency-management' version '1.0.10.RELEASE'
	id 'java'
	id 'war'
}

group = 'Spboot_Gradle'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	annotationProcessor 'org.projectlombok:lombok'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation('org.springframework.boot:spring-boot-starter-test') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
	implementation 'javax.servlet:jstl'
    implementation 'org.apache.tomcat.embed:tomcat-embed-jasper'
}

test {
	useJUnitPlatform()
}

 

(5) application.properties 설정 : 충돌을 방지하기 위한 포트번호, DB 계정 정보 등등 을 입력할 수 있습니다. (오타 조심!)

server.port = 8081

# JSP
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

# oracle set
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=scott
spring.datasource.password=tiger

(6) 반드시 5단계까지 완료하면  프로젝트의 마우스 우 > gradle > refresh gradle project 를해줘야 적용됩니다!

(7) 이제 sql작업을 합니다.

간단한 작업임으로 slq파일 업로드로 대체합니다.

sql.sql
0.00MB

(8) 이제 다음과 같이 체크한 부분은 직접 폴더를 만들고 파일을 생성하여 스프링 부트를 이용해 직접 db의 내용을 dto로 받아 dao로 sql문을 통해 jsp페이지에 값들을 뿌려보겠습니다.(체크 표시 : 만들어야 할 파일의 구조, 편하게 실습하시게 zip 파일로 프로젝트를 업로드했습니다.)

Spboot_Gradle_10_JdbcTemplate.zip
0.08MB

 

(9) 이제 실행해봅니다. 

방법 : boot dashboard에서 해당 프로젝트를 실행

(10)  오류가 발생했습니다..

아래는 오류 내용을 담은 console의 전체 부분입니다. 차근차근 해결해봐요 

 

- 문제: 내용을 살펴보면 application.properties에 입력한 datasource나 driver 등등 DB 연동에 문제가 발생함을 알 수 있습니다. 

 

<오류 console창>

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-10-20 23:19:28.258 ERROR 6528 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: oracle.jdbc.OracleDriver
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:655) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:635) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1336) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1176) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:556) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:516) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:324) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:322) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:897) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:879) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:551) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at com.spboot.g11.SpbootGradle11SimpleBbsApplication.main(SpbootGradle11SimpleBbsApplication.java:10) [main/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is java.lang.IllegalStateException: Cannot load driver class: oracle.jdbc.OracleDriver
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:650) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	... 20 common frames omitted
Caused by: java.lang.IllegalStateException: Cannot load driver class: oracle.jdbc.OracleDriver
	at org.springframework.util.Assert.state(Assert.java:97) ~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:223) ~[spring-boot-autoconfigure-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:175) ~[spring-boot-autoconfigure-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:43) ~[spring-boot-autoconfigure-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Hikari.dataSource(DataSourceConfiguration.java:85) ~[spring-boot-autoconfigure-2.3.4.RELEASE.jar:2.3.4.RELEASE]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_251]
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_251]
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_251]
	at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_251]
	at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.9.RELEASE.jar:5.2.9.RELEASE]
	... 21 common frames omitted

 

- 문제 해결

: 여러 가지 방법이 있겠지만 이번엔 직접 다음 경로에 직접 ojdbc6.jar를 복붙 해주었습니다.

경로 : C:\Program Files\Java\jre1.8.0_251\lib\ext 

 

(11) 다시 실행 

url에 "/user"  맵핑된 내용입력

 

- 정리

이번 시간엔 스프링 부트 프로젝트에 DB를 연결하고 뿌려오는 작업을 했다. 특히 ojdbc6.jar를 직접 복붙 하여 오류를 해결한 경험을 잘 기억하면 좋다고 생각한다.

728x90
LIST
Comments