[백업][가리사니] 스프링 4 입문강의 : 3. 데이터베이스 연동 ( mysql / 하이버네이트 )
java, jdbc, mysql, servlet, spring

이 문서는 가리사니 개발자 포럼에 올렸던 글의 백업 파일입니다. 오래된 문서가 많아 현재 상황과 맞지 않을 수 있습니다.

스프링 4 입문강의

서론

전 시간엔 Mustache 템플릿을 사용한 first 프로젝트를 만들어보았습니다. 이번엔 MySQL과 하이버네이트를 사용하여 한줄코멘트를 만들어보도록 하겠습니다. 이전 강의에서 만든 first 프로젝트를 이어서 사용할 것이기 때문에 아직 프로젝트를 만들지 않았다면 이전 강의를 참조하세요.

1. MySQL 설치

  • 윈도우에서 MySQL 설치는 과장 좀 하면 클릭질로 가능하기에.. 생략하도록 하겠습니다.
  • 위 주소를 참고해주세요.

2. MySQL 한줄 코멘트 만들기

  • 앞으로 사용할 스키마(데이터베이스) 를 만들어 봅시다.
  • 윈도우 한국어판을 사용하고 있다면 자동으로 유니코드(utf-8)이 되기 때문에 의미없어 보이나.
  • 리눅스의 경우 굳이 한국어로 깔지 않는 경우가 대부분이기 때문에 기본값이 라틴으로 인식될 수 있습니다.
  • 때문에 CHARACTER SET utf8 COLLATE utf8_general_ci; 는 같이 쓰는 것이 좋습니다.
CREATE SCHEMA `first` CHARACTER SET utf8 COLLATE utf8_general_ci;
  • first 유저를 만들어줍니다.
  • 계정 first / 암호 first
  • 권한 스키마 first / SELECT, INSERT, UPDATE, DELETE, EXECUTE, SHOW VIEW
  • 한줄코멘트 (simple_comment) 테이블 작성
CREATE TABLE `first`.`simple_comment` (
  `comment_no` INT NOT NULL AUTO_INCREMENT,
  `text` TEXT NOT NULL,
  `datetime` DATETIME NOT NULL  DEFAULT now(),
  PRIMARY KEY (`comment_no`));

3. pom 의존성 추가

  • pom.xml 의 사이에 아래 코드를 추가합니다.
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-jpamodelgen</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

4. MySQL / 하이버네이트 설정

  • src/main/resources/application.properties 열기.
  • 아래의 값을 추가해준다.
  • 마찬가지로 한국어 윈도우에선 기본 시스템값이 유니코드이기 때문에 문제가 되지 않지만.
  • 기타 시스템에선 기본값이 라틴일 가능성이 높기 때문에 useUnicode=yes&characterEncoding=utf-8 를 추가해 주시는게 좋습니다.
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/first?useSSL=true&useUnicode=yes&characterEncoding=utf-8
spring.datasource.username=first
spring.datasource.password=first
spring.jpa.generate-ddl=false
spring.jpa.show-sql=true
spring.jpa.database=mysql

5. 데이터베이스 접근 객체 만들기

  • com.first.jpa 패키지를 만듭니다.
  • SimpleComment 클래스를 추가하고 아래와 같이 작성합니다.
  • 나중에 롬복을 이용하여 저 지저분한 setter getter를 생략하는 법을 따로 강의하겠습니다.
package com.first.jpa;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name="simple_comment")
public class SimpleComment implements Serializable
{
	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	@Column(name="comment_no")
	private long comment_no;

	@Column(nullable = false)
	private String text;

	@Column(insertable = false, updatable = false)
	@Temporal(TemporalType.TIMESTAMP)
	private Date datetime;

	public long getComment_no()
	{
		return comment_no;
	}
	public String getText()
	{
		return text;
	}
	public void setText(String text)
	{
		this.text = text;
	}
	public Date getDatetime()
	{
		return datetime;
	}
}
  • SimpleCommentRepository 클래스를 추가하고 아래와 같이 작성합니다.
package com.first.jpa;

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

public interface SimpleCommentRepository extends JpaRepository<SimpleComment, Long>
{

}

6. 한줄코멘트 컨트롤러 만들기

  • com.first.controllers 에 SimpleCommentController 클래스를 추가하고 아래와 같이 작성합니다.
  • @Autowired 를 넣으면 자동으로 할당 관리해줍니다. (제어역전이 생소하다면 이상해 보일 수 있기에 설명.)
  • 마찬가지로 insert 함수의 파라미터도 자동으로 관리해줌으로 순서가 상관없습니다.
  • redirect: 를 넣으면 해당 url 로 리다이렉트 시켜줍니다.
package com.first.controllers;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.first.jpa.SimpleComment;
import com.first.jpa.SimpleCommentRepository;

@Controller
public class SimpleCommentController
{
	@Autowired
	private SimpleCommentRepository simpleCommentRepository;

	@RequestMapping("/SimpleComment/")
	public String view(Model model)
	{
		List<SimpleComment> commentList = simpleCommentRepository.findAll();
		model.addAttribute("CommentList", commentList);
		return "SimpleComment/simple-comment";
	}

	@RequestMapping("/SimpleComment/Insert")
	public String insert
	(
		Model model,
		HttpServletRequest request,
		@RequestParam("text") String text
	)
	{
		SimpleComment simpleComment = new SimpleComment();

		simpleComment.setText(text);
		simpleCommentRepository.save(simpleComment);

		return "redirect:/SimpleComment/";
	}
}

7. 한줄코멘트 뷰 만들기

  • /src/main/resources/templates/ 에 SimpleComment 디렉토리를 만들어줍니다.
  • simple-comment.html 파일을 생성하고 아래와 같이 입력합니다.
  • /src/main/resources/templates/SimpleComment/simple-comment.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>한줄코멘트</title>
</head>
<body>
	<!-- 보드 -->
	<table>
	
	<tr>
		<td></td>
		<td></td>
		<td></td>
	</tr>
	
	</table>

	<!-- 입력 -->
	<form id="comment-insert" method="post" action="/SimpleComment/Insert">
		<input type="text" name="text" placeholder="내용"/>
		<input type="submit" value="입력" />
	</form>

</body>
</html>

8. 실행