main
[MyBatis] CRUD 기본 구조 설정하기 본문
crud Project
1. Create model pakage
* VO (Value Object)
; database와 mapping되는 클래스 파일
현재는 model로 바뀜
2. Create repository pakage
* DAO(Data Access Object)
현재는 repository로 바뀜
3. Create service pakage, Create utils pakage
4. Create controller pakage
5. Create config pakage
1) DataAccessConfig.java
; pakage 이름 확인해서 변경하기
2) DataSourceConfig.java
6. application.yml 설정
server:
port: 8080
servlet:
context-path: /
spring:
mvc:
view:
prefix: /WEB-INF/views/
suffix: .jsp
datasource:
url: jdbc:mysql://localhost:3306/cos?serverTimezone=Asia/Seoul
driver-class-name: com.mysql.cj.jdbc.Driver
username: cos
password: Bitc5600!
7. src/main/resources 폴더에 mapper folder 생성
1) post.xml file 생성하고 mapper file 설정해주기
8. model package에 Post class file 생성
package com.cos.crud.model;
import java.sql.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data //getter,setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Post {
private int id;
private String title;
private String content;
private int userId; //FK
private Timestamp createDate;
}
9. repository package에 PostRepository(Interface) 생성
package com.cos.crud.repository;
import java.util.List;
import com.cos.crud.model.Post;
// 원래 방식은 @Repository가 필요하지만
// DataAccessConfig에서 MappeScan을 할 때
// 메모리(Spring Container)에 로드되고
// 싱글톤으로 관리된다.
public interface PostRepository {
List<Post> findAll();//전체보기
void save(Post post);//글쓰기
void update(Post post);//수정하기
void delete(int id);//삭제하기
Post findById(int id);//상세보기
}
10. controller package에 PostController file 생성
package com.cos.crud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.cos.crud.model.Post;
import com.cos.crud.repository.PostRepository;
@Controller
@RequestMapping("/post")
public class PostController {
@Autowired
private PostRepository postRepository;
// GET =] http://localhost:8080/post
// GET =] http://localhost:8080/post/
// Model은 데이터를 Controller에서 Presentation 계층까지 들고간다.
@GetMapping("")
public String post(Model model) {
List<Post> posts = postRepository.findAll();
model.addAttribute("posts", posts);
return "/post/list";
}
// POST =] http://localhost:8080/post/update
@PostMapping("/update")
public String update(Post post) {// param, form
try {
postRepository.update(post);
return "redirect:/post";
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:";
}
// GET =] http://localhost:8080/post/updateForm
@GetMapping("/updateForm/{id}")
public String updateForm(@PathVariable int id, Model model) {
Post post = postRepository.findById(id);
model.addAttribute("post", post);
return "post/updateForm";
}
// @RequestParam("id")
// @RequestBody = JSON
// POST =] http://localhost:8080/post/delete/1
@GetMapping("/delete/{id}")
public String delete(@PathVariable int id) {
try {
postRepository.delete(id);
return "redirect:/post";
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:";
}
// POST =] http://localhost:8080/post/save
@PostMapping("/save")
public String save(Post post) {
try {
postRepository.save(post);
return "redirect:/post";
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:";
}
// POST =] http://localhost:8080/post/1
@GetMapping("/{id}")
public String detail(@PathVariable int id, Model model) {
Post post = postRepository.findById(id);
model.addAttribute("post", post);
return "post/detail";
}
// GET =] http://localhost:8080/post/writeForm
@GetMapping("/writeForm")
public String writeForm() {
return "post/writeForm";
}
}
11. /crud/src/main/webapp/WEB-INF/views/post
- detail.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>제목 : ${post.title}</p>
<p>작성자 : ${post.userId}</p>
<p>작성일 : ${post.createDate}</p>
<p>내용 : ${post.content}</p>
<a href="/post/updateForm/${post.id}">수정하기</a>
<a href="/post/delete/${post.id}">삭제하기</a>
</body>
</html>
- list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1">
<tr>
<th>번호</th>
<th>제목</th>
<th>날짜</th>
</tr>
<c:forEach var="post" items="${posts}">
<tr>
<td>${post.userId}</td>
<td><a href="post/${post.id}"> ${post.title}</a></td>
<td>${post.createDate}</td>
</tr>
</c:forEach>
</table>
<a href="/post/writeForm">글쓰기</a>
</body>
</html>
- updateForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/post/save" method="post">
<input type="text" value="${post.title}" name="title" placeholder="title"><br>
<input type="hidden" value="${post.id}">
<textarea rows="5" cols="20" name="content">${post.content}</textarea><br>
<input type="submit" value="전송">
</form>
</body>
</html>
- writeForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/post/save" method="post">
<input type="text" name="title" placeholder="title"><br>
<textarea rows="5" cols="20" name="content"></textarea><br>
<input type="submit" value="전송">
</form>
</body>
</html>
12. post.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="com.cos.crud.repository.PostRepository">
<select id="findAll" resultType="com.cos.crud.model.Post">
SELECT * FROM post ORDER BY id DESC
</select>
<select id="findById" resultType="com.cos.crud.model.Post">
SELECT * FROM post WHERE id = #{id}
</select>
<insert id="save">
INSERT INTO post(title,content,userId,createDate)
VALUES(#{title},#{content},#{userId},now())
</insert>
<update id="update">
UPDATE post SET title =#{title},content= #{content}
WHERE ID=#{id}
</update>
<delete id="delete">
DELETE FROM post WHERE id = #{id}
</delete>
</mapper>
728x90
'Java > Spring' 카테고리의 다른 글
[Spring] Tomcat 10.1 다운로드 및 설정 (Java 11/Windows/Eclipse/STS) (0) | 2023.04.22 |
---|---|
[JUnit] fail() : Ambiguous method call. Both 에러 (0) | 2023.04.11 |
[Spring boot/Gradle] spring-boot-devtools 추가하기 (IntelliJ) (0) | 2023.04.11 |
[MyBatis] application.yml 설정, MyBatis 연결하기 (0) | 2022.10.01 |
[Spring] 스프링 설치 및 기본 설정 (2020년 버전) (0) | 2022.09.24 |
Comments