본문 바로가기
Java/└ Mybatis

Mybatis) 학생 정보 등록 - MAP

by 박채니 2022. 8. 5.

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

 

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


학생 정보 등록 - MAP

 

studentEnroll.jsp

<h2>학생등록(MAP)</h2>
<form method="POST" action="${pageContext.request.contextPath}/student/studentMapEnroll.do">
    <table>
        <tr>
            <th>학생이름</th>
            <td>
                <input type="text" name="name" required/>
            </td>
        </tr>
        <tr>
            <th>전화번호</th>
            <td>
                <input type="tel" name="tel" maxlength="11" required/>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="등록" />
            </td>
        </tr>
    </table>
</form>

 

Controller

StudentMapEnrollController

public class StudentMapEnrollController extends AbstractController {
	static final Logger log = Logger.getLogger(StudentMapEnrollController.class);
	private StudentService studentService;
	
	public StudentMapEnrollController(StudentService studentService) {
		super();
		this.studentService = studentService;
	}
	
	/**
	 * Student DTO -> Map<String, Object>
	 */
	@Override
	public String doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String name = request.getParameter("name");
		String tel = request.getParameter("tel");
		
		Map<String, Object> map = new HashMap<>();
		map.put("name", name);
		map.put("tel", tel);
		
		int result = studentService.insertStudentMap(map);
		
		request.getSession().setAttribute("msg", "학생을 성공적으로 등록하였습니다.");
		return "redirect:/student/studentEnroll.do";
	}
}

 

Service

StudentService (interface)

int insertStudentMap(Map<String, Object> map);

 

StudentServiceImpl

@Override
public int insertStudentMap(Map<String, Object> map) {
    SqlSession sqlSession = getSqlSession();
    int result = 0;

    try {
        result = studentDao.insertStudentMap(sqlSession, map);
        sqlSession.commit();
    } catch (Exception e) {
        sqlSession.rollback();
        throw e;
    } finally {
        sqlSession.close();
    }
    return result;
}

 

Dao

StudentDao (interface)

int insertStudentMap(SqlSession sqlSession, Map<String, Object> map);

 

StudentDaoImpl

@Override
public int insertStudentMap(SqlSession sqlSession, Map<String, Object> map) {
    return sqlSession.insert("student.insertStudentMap", map);
}

 

student-mapping.xml

<insert id="insertStudentMap" parameterType="map">
    insert into student(no, name, tel) values(seq_student_no.nextval, #{name}, #{tel})
</insert>

Map으로도 잘 등록 되는 것을 확인할 수 있으며, Mybatis 별칭을 이용하여 parameterType을 지정해주었습니다.