Mybatis-comment(insert,list,delete,update)

임재헌·2023년 5월 22일

Mybatis

목록 보기
3/6

insert

view


<!-- 댓글 -->
<div id="comment" style="padding-left:15px; font-size: 15px;">
<label for="content">댓글</label>
<form id="commentInsertForm" name="commentInsertForm">
	<div>
<input type="hidden" name="product_code" value="${product.PRODUCT_CODE}">
<input type="text" name="content" id="content" placeholder="댓글을 입력해주세요" autofocus>
<button type="button" name="commentInsertBtn" id="commentInsertBtn" class="btn btn-default">등록</button>
	</div>
</form>
	</div>

<!-- 댓글 목록 -->
<div id="clist" style="padding: 15px; padding-top: 10px; padding-bottom: 10px;">
<div class="commentlist"></div>
</div>

<script>
let product_code='${product.PRODUCT_CODE}';

//댓글 등록 버튼을 클릭한 경우
$("#commentInsertBtn").click(function(){
	//alert($);
    let insertData=$("#commentInsertForm").serialize();
   // alert(insertData);//product_code=7&content=11111111 부모글 번호, 내용

   //댓글 등록함수 호출
   commentInsert(insertData);
});

function commentInsert(insertData) {
    //alert("댓글 등록 함수"+insertData);
    $.ajax({url:'/comment/insert', //요청 명령어 등록
    type:'post', //넘기는방식
    data:insertData,
    error:function(error){
        alert(error);
    },
    success:function(data){
       //alert(data);
       if (data==1) {
        //전달 받은 데이터 값이 1 -> 댓글 등록이 성공한 경우
        commentList(); // 댓글 작성후 목록으로 이동

        //기존 댓글 내용을 빈 문자열로 대입
        $("#content").val('');

       }
    }});
}
</script>

controller

package kr.co.itwill.comment;

import java.util.List;

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

@Controller
@RequestMapping("/comment")
public class CommentController {
	public CommentController() {
		System.out.println("---CommentController 객체 생성");
	}

	@Autowired
	CommentDAO commentDao;

	@RequestMapping("/insert")
	@ResponseBody
	public int mCommentServiceInsert(@RequestParam int product_code, @RequestParam String content) throws Exception {
		// System.out.println(product_code);
		// System.out.println(content);
		CommentDTO comment = new CommentDTO();
		comment.setProduct_code(product_code);
		comment.setContent(content);

		// 로그인 기능을 구현했거나 따로 댓글 작성자를 입력받는 폼이 있다면
		// 입력 받아온 값으로 사용하면 된다
		// session.getAttribute();
		// 폼구현 x-> "test"
		comment.setWname("test");

		return commentDao.commentInsert(comment);
	}

DAO

package kr.co.itwill.comment;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CommentDAO {

	public CommentDAO() {
		System.out.println("---CommentDAO 객체 생성");
	}

	@Autowired
	SqlSession sqlSession;

	public int commentInsert(CommentDTO comment) {
		return sqlSession.insert("comment.insert", comment);
	}

MAPPER

<insert id="insert" parameterType="kr.co.itwill.comment.CommentDTO">
insert into pcomment(cno,product_code,content,wname)
values (pcomment_seq.nextval,#{product_code},#{content},#{wname} )
</insert>

insert확인


list

DAO

public List<CommentDTO> commentlist(int product_code) {
		return sqlSession.selectList("comment.list", product_code);
	}

controller

//map보다는 list가 관리하기 수월하다
	@RequestMapping("/list")
	@ResponseBody
	public List<CommentDTO> mCommentServiceList(@RequestParam int product_code) throws Exception{
		return commentDao.commentlist(product_code);
	}

mapper

<select id="list" resultType="kr.co.itwill.comment.CommentDTO" parameterType="int">
<![CDATA[
select *
from pcomment
where product_code=#{product_code}
order by regdate
]]>
</select>

view


function commentList() {
   // alert("댓글 목록 호출");

   // product_code 전달
    $.ajax({url:'/comment/list',
    type:'get',
    data:{'product_code':product_code},        // 넘기는 항목이 여러개 {}
    success:function(data){
        //alert(data);

        let a='';//출력할 결과 값  모두 a에 모은다

        $.each(data,function(key,value) {
            //alert(key);//0 1 2
            //alert(value);//[object object]
            
            /*  댓글 내용 확인
            alert(value.cno);
            alert(value.content);
            alert(value.wname);
            alert(value.regdate);
            alert(value.product_code);
            */
           a += value.content +"<br>";
        });
        $(".commentList").html(a);
    }});
}// ////////////////////////////

$(document).ready(function() {
   commentList(); 
   //상세목록 페이지로 들어온 경우 댓글목록 출력하기
});

행의 갯수만큼 object 반환

출력 결과 확인


delete

view

 
            //하나의 댓글당 div 작업
           a +='<div class="commentArea" style="border-bottom:1px solid darkgray; margin-bottom:15px;">'     
            // 댓글번호 + div
           a +='<div class="commentInfo'+value.cno+'">'
           a +='댓글번호:'+value.cno +' / 작성자:'+value.wname+" "+value.regdate;
           a += '<a href="javascript:commentDelete('+value.cno+')">[수정]</a>'+" ";
           a +='<a href="javascript:commentDelete('+value.cno+')">[삭제]</a>'; 
           a +='</div>' 
           //댓글 내용 div
           a +='<div class="commentContent'+value.cno+'">'         
           a +='<p> 내용: '+ value.content +"</p>";
           a +='</div>'
           a +='</div>'


/////////////////////////////댓글 삭제
//pk값 넘기기
function commentDelete(cno) {
 //   alert(cno);
 //댓글을 삭제하고 원래 위치로 돌아오기
 $.ajax({
    url:'/comment/delete/'+cno,  //  /comment/delete/+3
    type:'post',
    success:function(data){
        //alert(data);
        if (data==1) {
            commentList();
        }
    }
 });
}

DAO


	public int commentDelete(int cno) throws Exception{
		return sqlSession.delete("comment.delete",cno);
	}

CONTROLLER

	@RequestMapping("/delete/{cno}")
	@ResponseBody
	public int mCommentServiceDelete(@PathVariable int cno)throws Exception{
		return commentDao.commentDelete(cno);
	}

mapper

<delete id="delete" parameterType="int">
delete from pcomment
where cno=#{cno}
</delete>


댓글 수정

update

////////댓글 수정
//댓글 내용을 input에 출력
function commentUpdate(cno,content) {
    //alert(cno+content);
    let a='';
    a+='<div class="input-group">';
    a +='<input type="text" value="'+content+'" id="content'+cno +'">';
    a +='<button type="button" class="btn btn-default"token operator">+cno+')">수정</button>';
    a+='</div>';
   // alert(a);
   //div class=commentContent에 댓글 내용 출력
   $(".commentContent"+cno).html(a);
}
function commentUpdateProc(cno) {
    //let updateContent=$('[name=content_'+cno+']');
    let updateContent=$('#content'+cno).val();
    //alert(cno);
    $.ajax({
        url:'/comment/update',
        type:'post',
        data:{'content':updateContent,'cno':cno},
        success:function(data){
            if (data==1) {
                commentList();
            }
        }
    });
}

DAO

	public int commentUpdate(CommentDTO comment){
		return sqlSession.update("comment.update",comment);
	}

CONTROLLER

@RequestMapping("/update")
	@ResponseBody
	public int mCommentServiceUpdate(@RequestParam int cno, @RequestParam String content)throws Exception{
		CommentDTO comment=new CommentDTO();
		comment.setCno(cno);
		comment.setContent(content);
		return commentDao.commentUpdate(comment);
	}

MAPPER

<update id="update" parameterType="kr.co.itwill.comment.CommentDTO">
update pcomment
set content=#{content}
where cno=#{cno}
</update>

5개의 댓글

comment-user-thumbnail
2025년 4월 28일

pdating database entries like comments using structured queries is essential for keeping user-generated content accurate and fresh. Similarly, staying updated with the best streaming apps ensures you always have access to the latest entertainment. For a great Mod APK streaming option, check out https://freecineapp.com.br/, where you can easily watch movies and TV shows without limitations.

1개의 답글
comment-user-thumbnail
2025년 7월 13일

The MyBatis comment methods like insert, list, delete, and update are super useful for keeping database interactions clean and efficient. Whether you're building something lightweight or scalable, it's a solid choice. On a lighter note, if you're into relaxing after coding, check out this http://vape4usa.com—smooth and hassle-free, just like a well-written SQL mapper.

1개의 답글