Write it/Spring Boot

Spring Boot) H2 이용 질문 테이블 만들기

develop_mii 2025. 9. 8. 23:06

H2 데이터베이스 설치 / 설정

 

project 생성 시 dependencies 추가

 

 

# build.gradle

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	developmentOnly 'org.springframework.boot:spring-boot-devtools'
	runtimeOnly 'com.h2database:h2'
	annotationProcessor 'org.projectlombok:lombok'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

 

 

# application.properties

server.port=8888

#H2 Database DataSource
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:~/local
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

 

 

cmd창 : copy con local.mv.db - enter

            ctrl+z 누른 후 enter 

 

 

C드라이브 - 사용자 - pc설정한이름 폴더 안 - local.mv.db 파일 생성 확인

 

 

프로그램으로 돌아와서 조금 전 만든 project파일 서버 켜주고

 

 

웹브라우저 창에 

http://localhost:8888/h2-console 입력 → H2 DB 접속 화면 

 

jdbc:h2:~/local로 변경 → 연결 시험 성공 확인 후 → 연결 클릭

 


나머지 설정 

 

# application.properties

server.port=8888

#H2 Database DataSource
spring.h2.console.enabled=true
spring.h2.console.path=/h2-console
spring.datasource.url=jdbc:h2:~/local
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

# JPA config

# SQL Query가 콘솔창에 출력되는 설정
spring.jpa.properties.hibernate.show_sql=true

# SQL Query가 콘솔창에 가독성 좋게 변환해서 출력하는 설정
spring.jpa.properties.hibernate.format_sql=true

# SQL Query가 실행될 때 콘솔창에 파라미터 값이 오는 자리에 ?를 표시해주는 설정
logging.level.org.hibernate.type.descriptor.sql.spi=trace

# 데이터베이스 테이블 생성 관련한 옵션 설정
spring.jpa.hibernate.ddl-auto=update 

# 연결된 데이터베이스의 종류를 설정
# spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

 

 


질문 엔티티 만들기

 

[src/main/java]

 

# question entity 

import java.time.LocalDateTime;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor

@Entity  // DB와 매핑할 entity 클래스로 설정
public class Question {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id; // 질문 게시판의 글 번호 (기본키, 자동증가 옵션)
	
	@Column(length = 200) // 질문 게시판 제목은 200자까지 가능
	private String subject; // 질문게시판 제목
	
	@Column(columnDefinition = "TEXT") // 긴글도 가능
	private String content; // 질문 게시판 내용
	
	private LocalDateTime createDate;
}

 

 

파일 저장 후 서버 새로고침 하면  Question 테이블 만들어진 것 확인

 

 

# answer entity

import java.time.LocalDateTime;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Answer {
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id; //기본키, 자동증가
	
	@Column(columnDefinition = "TEXT")
	private String content;
	
	private LocalDateTime createDate;
	
	//N:1 -> 답변 : 질문 ->@ManyToOne
	@ManyToOne
	private Question question;


}

 

 

서버에서 ANSWER 테이블 생성 확인

*QUESTION_ID : ManyToOne 관계설정으로 생긴 외래키

 

 

# question entity 추가

1:N 관계 설정 추가

//1:N 관계 -> 질문 : 답변들 -> @OneToMany
	@OneToMany(mappedBy = "question", cascade = CascadeType.REMOVE) 
	//mappedBy에 적은값은 answer에서 설정한 이름 , cascade - 질문글(부모글)이 삭제 될 경우, 답글들이 함께 삭제되게하는 설정
	private List<Answer> answerList;

 

 

테이블 잘 생겼는지 확인

 


Repository 만들기 (인터페이스)

 

# QuestionRepository 

import org.springframework.data.jpa.repository.JpaRepository;

import com.kmii.kmiboard.entity.Question;

public interface QuestionRepository extends JpaRepository<Question, Integer> {
	
	public Question findBySubject(String subject);
	

}

 


Test 해보기

 

#Test1

import java.time.LocalDateTime;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.kmii.kmiboard.entity.Question;
import com.kmii.kmiboard.repository.QuestionRepository;

@SpringBootTest
public class Test01 {
	
	@Autowired
	private QuestionRepository questionRepository;
	
	@Test
	public void testJpa1() {
		Question q1 = new Question();
		q1.setSubject("sbb가 무엇인가요?"); //질문 제목
		q1.setContent("sbb에 대해 알고 싶습니다"); // 질문 내용
		q1.setCreateDate(LocalDateTime.now()); // 현재 시간 넣기
		//q1 -> entity 생성 완료
		questionRepository.save(q1);
		
		
		Question q2 = new Question();
		q2.setSubject("스프링부트 모델이 무엇인가요?"); //질문 제목
		q2.setContent("id는 자동 생성되는게 맞나요"); // 질문 내용
		q2.setCreateDate(LocalDateTime.now()); // 현재 시간 넣기
		//q1 -> entity 생성 완료
		questionRepository.save(q2);		
		
		
	}

}

 

중요) Test 파일 실행 전 켜져있는 서버 꺼주고 다시 실행
         그냥 실행 한다면 ‘The file is locked: nio:/Users/pahkey/local.mv.db’와 비슷한 오류 확률이 높다