
Dynamic SQL - 수정된 데이터만 보내기
이전 포스트에서 다룬 전체 데이터가 모두 들어왔다고 가정하고 진행이 되었다.
그렇기 때문에 만약 아이디, 비밀번호, 이름, 나이 등 여러 정보 중 하나만 수정하고 싶을 경우 기존 데이터와 수정된 데이터를 함께 보내서 update를 해왔다.
위 방식은 효율성이 떨어진다!
그래서 이번 포스트에서는 내가 수정한 값만 가져와서 서버로 전달한 후 동적쿼리를 통해 수정된 값만 update 하는 방법을 알아보고자 한다.
기능 설명
html
<form action="update.do" method="post">
<table>
<caption>${info.id} 님의 정보</caption>
<tr>
<th>ID</th>
<td><input type="text" name="id" value="${info.id}" readonly="readonly"/></td>
</tr>
<tr>
<th>PW</th>
<td><input type="password" name="pw" value="${info.pw}"/></td>
</tr>
<tr>
<th>NAME</th>
<td><input type="text" name="name" value="${info.name}"/></td>
</tr>
<tr>
<th class="co">AGE</th>
<td><input type="text" name="age" value="${info.age}"/></td>
</tr>
<tr>
<th class="co">GENDER</th>
<td>
<input type="radio" name="gender" value="남"
<c:if test="${info.gender eq '남'}">checked</c:if>/>남
<input type="radio" name="gender" value="여"
<c:if test="${info.gender eq '여'}">checked</c:if>/>여
</td>
</tr>
<tr>
<th class="co">EMAIL</th>
<td><input type="email" name="email" value="${info.email}"/></td>
</tr>
<tr>
<th colspan="2">
<input type="button" value="수정요청" onclick="update()"/>
</th>
</tr>
</table>
</form>
info 라는 key로 넘겨준다.java script
function update(){
var param = {id:'${info.id}'};
$('form input').each(function(idx,item){
var type = $(item).attr('type');
if(type == 'radio'){
if($(item)[0].defaultChecked != $(item)[0].checked && $(item)[0].checked){
param[$(item).attr('name')] = $(item).val();
}
}else{
if($(item)[0].defaultValue != $(item)[0].value){
param[$(item).attr('name')] = $(item).val();
}
}
});
$.ajax({
type: 'POST',
url: 'update.ajax',
data: param,
dataType: 'JSON',
success: function(data){
console.log(data);
if(data.success){
alert('수정에 성공했습니다.');
location.href='detail.do?id=${info.id}';
}else{
alert('수정에 실패했습니다.');
}
},error: function(e){
console.log(e);
}
})
}
id,pw,name,age,gender,email 중에서 변경이 생긴 값만 파라미터로 전달
ID 값을 변수에 담아준다. (변경이 발생하면 안됨)
input 태그를 반복하며 안에있는 값을 가져온다.
기존에 있던 값과 변동된 값이 있을 경우 param 에 담아준다.
ridio : defaultChecked (기존값) / checked (바뀐 값)
▶ 기존값과 바뀐 값이 다르면서 checked 인 요소로 바꿔줘야 한다. (변동된 값의 value)
text : defaultValue (기존값) / Value (바뀐 값)
▶ 기존값과 바뀐값이 다르면 param 에 넣어준다.
key 에 컬럼명(input[type=name]) 을 넣고, value 에 해당 태그의 .val() 을 넣는다.
$.ajax({}) 를 사용해 서버로 값을 보내준다.
▶ 성공할 경우(success == ture) alert + detail 페이지로 이동
▶ 실패할 경우 alert
@RequestMapping(value="/detail.do")
public String detail(String id, Model model) {
MemberDTO dto = member_service.detail(id);
model.addAttribute("info", dto);
return "detail";
}
@PostMapping(value="/update.ajax")
@ResponseBody
public Map<String, Object> update(@RequestParam Map<String, String> param){
Map<String, Object> result = member_service.update(param);
return result;
}
service
public MemberDTO detail(String id) {
return member_dao.detail(id);
}
public Map<String, Object> update(Map<String, String> param){
int row = member_dao.update(param);
Map<String, Object> map = new HashMap<>();
map.put("success", row>0?true:false);
return map;
}
dao
MemberDTO detail(String id);
int update(Map<String, String> params);
<select id="detail" resultType="kr.co.gudi.dto.MemberDTO" parameterType="String">
SELECT * FROM member WHERE id = #{id}
</select>
<update id="update" parameterType="map">
UPDATE member
<set>
<if test="pw != null and pw != ''">
pw = #{pw},
</if>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="gender != null and gender != ''">
gender = #{gender},
</if>
<if test="email != null and email != ''">
email = #{email},
</if>
</set>
WHERE id = #{id}
</update>
<set></set> 을 사용해 값이 없더라도 노출되지 않도록 한다.<set> 안의 조건식에서 일치하는 조건이 있으면 SET절을 만들어 반환하고 없으면 만들지 않는다., 를 노출시키고 다음값이 없으면 , 를 지워준다.