반응형

개요

- SpringBoot에 MySQL을 연동해본다.

- SpringBoot에 JPA를 연동해본다.

- MySQL과 JPA를 연동 후, 테스트 오브젝트인 Memo 객체를 만들어서, SpringBoot를 실행한다.

- (확인포인트) 실행 후에, 정상적으로 설정된 MySQL DB에 Memo 테이블이 생성이 되어있는지 확인한다.

 

- (사전사항) MySQL이 설치가 되어있어야 함. (MySQL에서 Database는 만들어져있는 상태여야 함)

 

수정사항

- dependency 추가

dependencies {

    implementation 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

}

 

[PROJECT]/build.gradle

(추가된부분) 참고

plugins {
	id 'org.springframework.boot' version '2.6.2'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'mysql:mysql-connector-java' // (추가된부분)
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa' // (추가된부분)
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
	useJUnitPlatform()
}

 

- application.properties 변경

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

# DB Source URL 설정
# 예시) spring.datasource.url=jdbc:mysql://localhost:3306/test_db?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul
spring.datasource.url=jdbc:mysql://<IP>:<PORT>/<DB NAME>?useSSL=false&useUnicode=true&serverTimezone=Asia/Seoul


# DB 사용자 이름 설정
# 예시) spring.datasource.username=root
spring.datasource.username=<MySQL ID>

# DB 사용자이름에 대한 암호 설정
# 예시) spring.datasource.password=root
spring.datasource.password=<MySQL PASSWORD>

# true 설정 시, JPA 쿼리문 확인 가능
spring.jpa.show-sql=true

# DDL(create, alter, drop) 정의 시, DB의 고유 기능을 사용할 수 있음.
spring.jpa.hibernate.ddl-auto=update 

# JPA의 구현체인 Hibernate가 동작하면서, 발생한 SQL의 가독성을 높여줌.
spring.jpa.properties.hibernate.format_sql=true

 

 

- SpringJpaApplication.java    (main/java/com.example.spring_jpa/SpringJpaApplication, 메인 애플리케이션)

@RestController
@SpringBootApplication
public class SpringJpaApplication {
	@RequestMapping("/")
	String home() {
		return "Hello World!";
	}
	public static void main(String[] args) {
		SpringApplication.run(SpringJpaApplication.class, args);
	}
}

 

- Memo.java    (main/java/com.example.spring_jpa/Memo.java)

@Entity
@Table(name = "tbl_memo")
public class Memo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(length = 200, nullable = false)
    private String memoTextselet;
}

@Table : 원하는 테이블 명을 입력해준다. 그래야, 해당 테이블로 객체가 생성되기 때문이다.

 

결과화면

테이블이 잘 생성된 걸 확인할 수 있다.

1. 아래의 명령어로 접속.

# mysql -u root -p

 

2. 데이터베이스 선택

mysql> use test_db

 

3. 테이블 확인

mysql> show tables;

 

 이로써, SpringBoot, MySQL, JPA 셋을 연동하여, 테이블 생성까지 완료하였다.

반응형