본문 바로가기
Java/Spring

Spring) DB 등록 - 개발자 정보 등록 (StringTypeHandler)

by 박채니 2022. 8. 18.

안녕하세요, 코린이의 코딩 학습기 채니 입니다.

 

개인 포스팅용으로 내용에 오류 및 잘못된 정보가 있을 수 있습니다.


 

DB 등록 - 개발자 정보 등록

 

devForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<jsp:include page="/WEB-INF/views/common/header.jsp">
	<jsp:param value="Dev등록" name="title"/>
</jsp:include>
<style>
div#demo-container{
	width:550px;
}
</style>

<div id="demo-container" 
	 class="border border-secondary mx-auto p-3 rounded">
	<!-- https://getbootstrap.com/docs/4.1/components/forms/#readonly-plain-text -->
	<form name="devFrm">
		<div class="form-group row">
		  <label for="name" class="col-sm-2 col-form-label">이름</label>
		  <div class="col-sm-10">
		    <input type="text" class="form-control" id="name" name="name" required>
		  </div>
		</div>
		<div class="form-group row">
		  <label for="career" class="col-sm-2 col-form-label">개발경력</label>
		  <div class="col-sm-10">
		    <input type="number" class="form-control" id="career" name="career" value="0" required>
		  </div>
		</div>
		<div class="form-group row">
		  <label for="email" class="col-sm-2 col-form-label">이메일</label>
		  <div class="col-sm-10">
		    <input type="email" class="form-control" id="email" name="email" required>
		  </div>
		</div>
	  	<!-- https://getbootstrap.com/docs/4.1/components/forms/#inline -->
	    <div class="form-group row">
	    	<label class="col-sm-2 col-form-label">성별</label>
	    	<div class="col-sm-10">
			    <div class="form-check form-check-inline">
				  <input class="form-check-input" type="radio" name="gender" id="gender0" value="M">
				  <label class="form-check-label" for="gender0">남</label>
				</div>
				<div class="form-check form-check-inline">
				  <input class="form-check-input" type="radio" name="gender" id="gender1" value="F">
				  <label class="form-check-label" for="gender1">여</label>
				</div>
			</div>
		</div>
		<div class="form-group row">
			<label class="col-sm-2 col-form-label">개발언어</label>
			<div class="col-sm-10">
				<div class="form-check form-check-inline">
				  <input class="form-check-input" type="checkbox" name="lang" id="Java" value="Java">
				  <label class="form-check-label" for="Java">Java</label>
				</div>
				<div class="form-check form-check-inline">
				  <input class="form-check-input" type="checkbox" name="lang" id="C" value="C">
				  <label class="form-check-label" for="C">C</label>
				</div>
				<div class="form-check form-check-inline">
				  <input class="form-check-input" type="checkbox" name="lang" id="Javascript" value="Javascript">
				  <label class="form-check-label" for="Javascript">Javascript</label>
				</div>	
				<div class="form-check form-check-inline">
				  <input class="form-check-input" type="checkbox" name="lang" id="Python" value="Python">
				  <label class="form-check-label" for="Python">Python</label>
				</div>
			</div>
		</div>
	</form>
	<!-- 전송버튼  -->
	<div class="list-group">
	  <button type="button" onclick="submit('dev1');" class="list-group-item list-group-item-action">파라미터 핸들링 - HttpServletRequest</button>
	  <button type="button" onclick="submit('dev2');" class="list-group-item list-group-item-action">파라미터 핸들링 - @RequestParam</button>
	  <button type="button" onclick="submit('dev3');" class="list-group-item list-group-item-action">파라미터 핸들링 - Command 객체</button>
	  <button type="button" onclick="submit('insertDev');" class="list-group-item list-group-item-action">DB에 dev등록</button>
	</div>
</div>
<script>
const submit = (id) => {
	const frm = document.devFrm;
	frm.action = `${pageContext.request.contextPath}/demo/\${id}.do`;
	frm.method = 'POST';
	frm.submit();
}
</script>
<jsp:include page="/WEB-INF/views/common/footer.jsp"/>

 

Controller

DemoController

@RequestMapping(path = "/demo/insertDev", method = RequestMethod.POST)
public String insertDev(Dev dev, RedirectAttributes redirectAttr) {
    int result = demoService.insertDev(dev);
    redirectAttr.addFlashAttribute("msg", "개발자 등록 성공!");

    return "redirect:/";
}

RedirectAttributes의 addFlashAttribute()는 사용자의 피드백에 관련된 정보를 session에 저장되고 단 한 번만 출력 후 사라집니다.

 

Service

DemoService interface 생략

DemoServiceImpl

@Service
public class DemoServiceImpl implements DemoService {
	@Autowired
	private DemoDao demoDao;
	
	@Override
	public int insertDev(Dev dev) {
		return demoDao.insertDev(dev);
	}
}

 

Dao

DemoDao interface 생략

DemoDaoImpl

@Repository
public class DemoDaoImpl implements DemoDao {
	@Autowired
	private SqlSessionTemplate sqlSession;
	
	@Override
	public int insertDev(Dev dev) {
		return sqlSession.insert("demo.insertDev", dev);
	}
}

 

demo-mapper.xml

<mapper namespace="demo">
	<insert id="insertDev">
		insert into dev values(seq_dev_no.nextval, #{name}, #{career}, #{email}, #{gender}, #{lang}, default)
	</insert>
</mapper>

여기서 lang은 String[] 타입인데, 이를 jdbc에서 받을 타입이 없습니다.

따라서 타입 핸들러를 별도 생성하여 처리해주겠습니다.

 

StringArrayTypeHandler

@MappedTypes(String[].class) // javaType
@MappedJdbcTypes(JdbcType.VARCHAR) // jdbcType
public class StringArrayTypeHandler extends BaseTypeHandler<String[]> {

	/**
	 * String[] -> VARCHAR
	 * - parameter가 null인 경우는 호출되지 않음
	 */
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, String[] parameter, JdbcType jdbcType)
			throws SQLException {
		String value = String.join(",", parameter);
		ps.setString(i, value);
	}

	/**
	 * VARCHAR -> String[]
	 * - null이 올 수도 있기 때문에 분기처리 필요!
	 */
	@Override
	public String[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String value = rs.getString(columnName);
		return value != null ? value.split(",") : null;
	}

	@Override
	public String[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String value = rs.getString(columnIndex);
		return value != null ? value.split(",") : null;
	}

	@Override
	public String[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String value = cs.getString(columnIndex);
		return value != null ? value.split(",") : null;
	}

}

 

mybatis-config.xml 등록

<typeHandlers>
<!-- <typeHandler handler="com.kh.spring.common.typehandler.StringArrayTypeHandler" /> -->
<package name="com.kh.spring.common.typehandler"/> 
</typeHandlers>

String[]이 넘어오게 되면 해당 핸들러 클래스가 실행되어 처리해줍니다.