Notice
Recent Posts
Recent Comments
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
10-10 22:21
Archives
Today
Total
관리 메뉴

Developer_Neo

[Spring 입문] - 데이터베이스 연동(spring boot + Mysql with build.gradle , applicatioin.properties) 본문

Spring

[Spring 입문] - 데이터베이스 연동(spring boot + Mysql with build.gradle , applicatioin.properties)

_Neo_ 2022. 8. 4. 23:11
반응형
김영한님의 Spring입문 강의 내에서 database를 h2로 진행하였다. 하지만 나는 h2를 설치하기 싫어서 사용해왔던 Mysql으로 이용하였다.

 

build.gradle

추가한 코드

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'

	//밑이 추가한 코드들이다
	implementation 'org.springframework.boot:spring-boot-starter-jdbc'
	//implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'mysql:mysql-connector-java'
	implementation 'com.h2database:h2'
	runtimeOnly 'mysql:mysql-connector-java'
}

 

 

applicatioin.properties

# MySQL Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# db source url
spring.datasource.url=jdbc:mysql://localhost:3306/springintroduction?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true

# db response name
spring.datasource.username=root //mysql기준으로 GUI환경으로 들어갈때 사용자이름 확인 가능합니다.

# db response password
spring.datasource.password=____ //아시는 것으로 넣으시면 됩니다

여기에서 localhost:3306 다음에 springintroductioin을 볼 수 있는데 이것은 Mysql내의 스키마에 해당하는 것으로 자신이 생성한 스키마이며, 이용하고 싶은 스키마로 넣어주면 된다.

예시

 

그리고 기존에 작성했었던 MemoryMemberRepository 클래스 파일이 아닌 JdbcMemberRepository 클래스 파일을 만들어 진행하였다. 

Jdbc MemberRepository 클래스파일의 대략적인 모습

위에서 DataSource라는 것이 보일 것이다. 이것은 따로 스프링 빈등록을 안해주어도 스프링 부트가 스프링 빈으로 자동 등록해준다. 그래서 @Autowired로 주입만 시켜주면 된다.

 

추가적인 사항은 인프런의 김영한님의 Spring입문을 통해 알 수 있다.

 

이후 SpringConfig파일을 수정해주면 된다.

 

 


Mysql

create table member
(
 id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
 name varchar(255)
);

SELECT * FROM member;
insert into member(name) VALUES("spring");
insert into member(name) VALUES("spring2");

위에 해당하는 쿼리문으로 기본적으로 setting해놓았다.

 


결과

결과 이미지

회원 가입으로 이름을 jpa를 설정하고 회원 목록을 조회한 결과이다

반응형
Comments