2024-01-29(36일차) - Spring

민짱·2024년 1월 29일

📅2024. 01. 29 36일차


🎬2024_01_Spring_AM 구현 시작

C, R, U, D 구현

  • 어노테이션 사용
@Autowired
	private ArticleService articleService;

	public UsrArticleController() {

	}

	// 액션 메서드

	@RequestMapping("/usr/article/getArticle")
	@ResponseBody
	public Object getArticleAction(int id) {
		Article article = articleService.getArticle(id);

		if (article == null) {
			return id + "번 글은 존재하지 않습니다.";
		}

		return article;
	}

	@RequestMapping("/usr/article/doModify")
	@ResponseBody
	public Object doModify(int id, String title, String body) {

		Article article = articleService.getArticle(id);

		if (article == null) {
			return id + "번 글은 존재하지 않습니다.";
		}

		articleService.modifyArticle(id, title, body);

		return article;
	}

	@RequestMapping("/usr/article/doDelete")
	@ResponseBody
	public String doDelete(int id) {

		Article article = articleService.getArticle(id);

		if (article == null) {
			return id + "번 글은 존재하지 않습니다.";
		}

		articleService.deleteArticle(id);

		return id + "번 글이 삭제 되었습니다";
	}

	@RequestMapping("/usr/article/doWrite")
	@ResponseBody
	public Article doWrite(String title, String body) {
		Article article = articleService.writeArticle(title, body);
		return article;
	}

	@RequestMapping("/usr/article/getArticles")
	@ResponseBody
	public List<Article> getArticles() {
		return articleService.getArticles();
	}
}

리펙토링

  • ArticleRepository 인터페이스로 만들어 어노테이션을 이용해 sql쿼리를 날릴 수 있는 로직으로 구현
public interface ArticleRepository {

	@Insert("""
			INSERT INTO
			article SET
			regDate = NOW(),
			updateDate = NOW(),
			title = #{title}, `body` = #{body}
			""")
	public void writeArticle(String title, String body);

	@Select("SELECT LAST_INSERT_ID()")
	public int getLastInsertId();

	@Select("SELECT * FROM article WHERE id = #{id}")
	public Article getArticle(int id);

	@Delete("DELETE FROM article WHERE id = #{id}")
	public void deleteArticle(int id);

	@Update("UPDATE article SET updateDate = NOW(), title = #{title}, `body` = #{body} WHERE id = #{id}")
	public void modifyArticle(int id, String title, String body);

	@Select("SELECT * FROM article ORDER BY id DESC")
	public List<Article> getArticles();

}

현재 doModify할때 둘 다 입력해야만 수정된다.

  • 나는 제목(내용)만 바꾸고 싶은데??? 구현~

동적 sql

  • MyBatis에서 상황에 따라서 분기처리를 하는 유동적으로 동작하는 SQL 쿼리문을 뜻한다.
  • 사용될 sql문이 return시에 결정되는 sql문
<update id="modifyArticle">
		UPDATE article 
		<set>
			<if test="title != null and title != ''">title = #{title},</if>
			<if test="body != null and body != ''">`body` = #{body},</if>
			updateDate = NOW()
		</set> 
		WHERE id = #{id}
</update>

0개의 댓글