본문 바로가기
Spring/Spring Boot

[SpringBoot] DataBase를 연동한 게시판 구현2

by dbjh 2019. 12. 4.
반응형

지난 시간에는 데이터베이스를 설치하고 DB developer tool을 이용해 쿼리를 실행하는 단계 까지 진행하였다. 이번 시간에는 Spring boot의 설정값 및 필요한 파일들을 추가하여 Postgresql DB와 연결해보도록 하자.

 

1. Mybatis 및 Postgresql 의존성 주입을 위한 gradle 설정

- Mybatis 및 Postresql 관련 라이브러리를 사용하기 위해 application.properties 파일의 dependencies에 Mybatis와 Postgresql의 디펜던시를 추가하도록하자.

 

build.gradle

// 코드중략


dependencies {
	// 기존에 있던 문구들
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    compile "org.springframework.boot:spring-boot-starter-thymeleaf"
    
    // 아래 두 문구를 추가
    compile group: 'org.postgresql', name: 'postgresql', version: '42.1.4'
    compile group: 'org.mybatis.spring.boot', name: 'mybatis-spring-boot-starter', version: '1.3.2'
}

 

2. Postgresql DataBase 연결

- Gradle Reimport를 하여 라이브러리 추가가 완료되었다면 DB 연결을 위해  application.properties에 DB 연결정보 설정을 추가하도록하자.

 

추가된 라이브러리 확인

 

application.properties

// 코드중략

# 아래의 문구추가

# database settings
spring.datasource.url=jdbc:postgresql://localhost:5432/board
spring.datasource.username=postgres
spring.datasource.password=비밀번호

- 파일을 위와 같이 수정한 후에 프로젝트를 실행하여 문제없이 DB와 연결되는지 확인한다. 

 

프로젝트 실행 확인

 

* 프로젝트를 실행 하였는데 아래와같은 오류가 나는 경우가 있다.

***************************

APPLICATION FAILED TO START

***************************

 

Description:

 

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.


Reason: Failed to determine a suitable driver class 

 

 

- gradle Reimport 후에 application.properties의 설정 값을 다시 확인하도록 한다.

 

3. Mybatis 폴더 및 xml 파일 생성

-  DB 연결이 문제없이 되었다면, Mybatis를 위한 폴더 구조를 아래와 같이 생성하고 xml파일도 추가하도록하자.

 

Mybatis 관련 폴더 및 xml 파일 구조

 

 

configuration.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>
	<typeAliases>
		<typeAlias type="com.example.practice.vo.BoardVo" alias="boardvo"/>
	</typeAliases>
	<mappers>
		 <mapper resource="mybatis/mapper/board.xml" />
	</mappers>
</configuration>

- Vo 클래스의 폴더경로를 입력하고 별칭(alias)을 정해준다. 해당 별칭은 객체 형태 그대로 쿼리가 입력될 xml 파일에서 사용된다. -> 아래의 board.xml 파일을 보면 결과 형태를 지칭하는 resultType = 'boardvo'로 사용한다.

 

 

board.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="board">

	<select id="getBoardList" resultType="boardvo">
	<![CDATA[
		select board_no as no, board_title as title, contents, writer_name as userName, reg_date as regDate
		from board
	]]>
	</select>
</mapper>

 

4. Mybatis 설정 파일을 이용하기 위한 BoardDao.java 파일 수정

- Mybatis 라이브러리에 포함 되어있는 SqlSession 클래스를 이용하여 board.xml의 쿼리를 실행 시켜서 결과를 얻는 코드를 작성하자. 상당히 간단한 코드만 작성하면된다.

 

BoardDao.java

// 코드중략

@Repository
public class BoardDao {

    @Autowired
    private SqlSession sqlSession;

    public List<BoardVo> selectBoardList() {

        List<BoardVo> boardList = sqlSession.selectList("board.getBoardList");

        return boardList;
    }
}

- 위와 같이 코드를 구성하면 SqlSesion 객체의 selectList() 메소드를 실행될 것이다. select 쿼리를 실행한 결과가 여러개로 예상될 경우 사용하는 메소드이다. 이 메소드의 인자 값을 보면 "board.getBoardList"의 문자열이 들어간다. 

board는 위 board.xml <mapper> 태그를 보면 namespace="board"로 명시되어 있다. 바로 해당 <mapper>태그와 매핑 시키기 위해 넣어둔 값이다. 

<mapper>의 내부에는 <select> 태그가 있는데, <select> 태그의 id를 확인해보면 getBoardList로 되어있다. 그래서 결국 "board.getBoardList"를 인자로 넣어주는 이유는 namespace="board"<mapper> 태그 안에 id="getBoardList"<select> 태그의 쿼리를 실행 시키기 위해서이다. 

 

 

5. 프로젝트 실행 후 게시판 페이지 접근하기

- 모든 설정 및 코드를 수정하고 프로젝트를 실행 후, 게시판 페이지로 접근 하면, 

 

오류가 발생한 게시판 페이지

- ??? 왜 오류가 나지? 콘솔에 찍힌 에러 로그를 확인해보자

2019-12-03 23:51:46.531 ERROR 7000 --- [nio-8088-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException: 
### Error querying database.  Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for board.getBoardList
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for board.getBoardList] with root cause

 

- 말그대로 잘못된 인자를 넣어줘서 나는 오류이다. 매핑된 Collection이 borad.getBoardList를 위한 값을 포함하고 있지 않다는 것이다.

 

마이바티스 프레임워크 내부의 xml파일의 태그 매핑을 관리하는 객체에게 borad.getBoardList가 무엇인지 알려줘야한다. application.properties에 아래의 문구를 추가하여 mybatis의 설정파일(configuration.xml)이 어디있는지 알려주도록하자.

 

 

application.properties

# 아래의 문구 추가

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

 

- 다시 프로젝트를 빌드하고 시작한 후, 게시판 페이지로 접근하면,

 

 

Postgresql DataBase에서 읽어온 데이터를 화면에 뿌려주는 것을 확인할 수 있다.

반응형

댓글