Spring
[MyBatis] 동적 SQL / parameterType이 TO클래스가 아닌 java.util.List 클래스로 전달 후 insert / <foreach> 활용
bkuk
2022. 12. 23. 12:37
동적 SQL
MyBatis – 마이바티스 3 | 동적 SQL
동적 SQL 마이바티스의 가장 강력한 기능 중 하나는 동적 SQL을 처리하는 방법이다. JDBC나 다른 유사한 프레임워크를 사용해본 경험이 있다면 동적으로 SQL 을 구성하는 것이 얼마나 힘든 작업인지
mybatis.org
<%@page import="java.util.ArrayList"%>
<%@page import="model1.DeptTO"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<%@ page import="java.io.IOException" %>
<%@ page import="java.io.InputStream" %>
<%@ page import="java.util.List" %>
<%@ page import="org.apache.ibatis.io.Resources" %>
<%@ page import="org.apache.ibatis.session.SqlSession" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactory" %>
<%@ page import="org.apache.ibatis.session.SqlSessionFactoryBuilder" %>
<%
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
StringBuilder sbHtml = new StringBuilder();
try {
is = Resources.getResourceAsStream( resource );
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build( is );
sqlSession = sqlSessionFactory.openSession( true );
DeptTO to1 = new DeptTO();
to1.setDeptno( "11" );
to1.setDname( "생산" );
to1.setLoc( "부산" );
DeptTO to2 = new DeptTO();
to2.setDeptno( "12" );
to2.setDname( "연구" );
to2.setLoc( "부산" );
List<DeptTO> lists = new ArrayList<DeptTO>();
lists.add( to1 );
lists.add( to2 );
int result = sqlSession.insert( "insertall", lists );
System.out.println( "결과 : " + result );
} catch (IOException e) {
System.out.println( "[에러] " + e.getMessage() );
} finally {
if( sqlSession != null ) sqlSession.close();
if( is != null ) try { is.close(); } catch ( IOException e) {}
}
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
</head>
<body>
</body>
</html>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mybatis1">
<insert id="insertall" parameterType="java.util.List">
insert into dept2
values
<foreach collection="list" item="item" separator=",">
(
#{item.deptno}, #{item.dname}, #{item.loc}
)
</foreach>
</insert>
</mapper>