코디잉

[Maven] Spring Boot에서 MyBatis, H2 Database 사용 설정 본문

Spring

[Maven] Spring Boot에서 MyBatis, H2 Database 사용 설정

yong_ღ'ᴗ'ღ 2022. 11. 21. 02:48

 Maven 의존성 설정 (MyBatis & H2 Database)

    pom.xml 파일의 <dependencies> 태그 안에, 사용할 외부 라이브러리 정보를 설정하면 된다.

      (사용할 라이브러리가 Maven Repository에 등록되어 있어야 함)

        pom: Project Object Model

             pom.xml: Maven이 프로젝트를 빌드하기 위해 필요한 정보를 기술하는 XML 파일

 

pom.xml

<dependencies>
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.2</version>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
    </dependency>
</dependencies>

 

 

 application.properties 설정

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:~~:~~
spring.datasource.username=유저이름입력
spring.datasource.password=비밀번호입력

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

mybatis.config-location=classpath:mybatis/mybatis-config.xml

 

↓ 설명

 

spring.datasource.driver-class-name=org.h2.Driver
//--→ (MySql 경우)  com.mysql.cj.jdbc.Driver
//--→ (Oracle 경우) oracle.jdbc.driver.OracleDriver

spring.datasource.url=jdbc:h2:~~:~~
//--→ (DB 접속할 때) [protocol]:[host][port, db/schema명 등]
//    ex) jdbc:mysql://localhost:3306/post

spring.datasource.username=유저이름입력
spring.datasource.password=비밀번호입력

→  SpringBoot에서 SpringBoot에서 H2 Database를 Embedded 형식으로 사용할 때,
     즉, Maven 의존성 만으로 사용할 때에는
     위에 기술한 정보로 DB가 생성도 되고, 접속도 된다.

 

// H2 console 정보 설정
spring.h2.console.enabled=true
//--> H2 DB 사용할 때, 웹 콘솔 사용하겠다는 의미
spring.h2.console.path=/h2-console
//--> 웹 콘솔의 URI Path는 '/h2-console'로 하겠다는 의미

이렇게 설정한 후에, localhost:8081/h2-console로 접속 후,
     설정한 url, username, pw 입력하고 Connect 누르면,
     웹 기반 콘솔에 로그인 할 수 있다.

 

→ Spring 프로젝트의 resources > schema.sql 파일 만들고, 테이블 생성, 제거 등의 SQL 작성하면,  

     SpringBoot 애플리케이션 시작 시점에 schema.sql의 쿼리문이 자동으로 실행된다.

 

// MyBatis 설정
mybatis.config-location=classpath:mybatis/mybatis-config.xml

 

 

resources > new directory: mybatis > mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
	"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<mappers>
		<mapper resource="mybatis/mapper/todo-mapper.xml"/>
					:
			사용하는 mapper 들 넣어주면 됨
					:
	</mappers>
</configuration>

 

'Spring' 카테고리의 다른 글

Thymeleaf (타임리프)  (0) 2022.12.10
[Gradle] spring-boot-devtools 추가  (0) 2022.12.09
Spring Bean 생성  (0) 2022.11.20
@Service  (0) 2022.11.17
주요 HTTP Method  (0) 2022.11.16
Comments