Java를 위한 프레임워크
* 프레임워크 - 짜여진 틀
틀에 대한 문법
- 편리
- 자유
* MyBatis(iBatis)
SQL을 효율적으로 사용하기 위한 프레임워크
→ sql mapper
1. 라이브러리 ( Library )
2. 환경설정
1. log 출력용
log4j
2. Mybatis 환경
3. sql mapper 파일
// log4j.xml
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1}:%-3L) %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="console"/>
</root>
</log4j:configuration>
// myBatisConfig.xml
<?xml version= "1.0" encoding ="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="mariadb1">
<environment id="mariadb1">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3306/sample" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
<environment id="mariadb2">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3306/project" />
<property name="username" value="project" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
</configuration>
// MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.session.TransactionIsolationLevel;
public class MyBatisEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( is != null )
try { is.close(); } catch( IOException e ) {}
}
}
}
<!-- mapper.xml -->
<mapper namespace="mybatis" >
<select id="select1" resultType="DeptTO" >
select deptno, dname, loc
from dept
where deptno=10;
</select>
</mapper>
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisEx03 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
sqlSession = sqlSessionFactory.openSession();
System.out.println( "데이터베이스와 연결됨" );
DeptTO to = (DeptTO)sqlSession.selectOne( "select1" );
System.out.println( to.getDeptno() );
System.out.println( to.getDname() );
System.out.println( to.getLoc() );
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
selectOne은 결과가 하나만 실행 (여러개면 에러)
결과 데이터가 없으면 NullPointException 에러뜸
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Set;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisEx04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
sqlSession = sqlSessionFactory.openSession();
System.out.println( "데이터베이스와 연결됨" );
Map map = sqlSession.selectOne( "select5" );
Set<String> keys = map.keySet();
for( String key : keys) {
// 컬럼명
// System.out.println( key );
System.out.println( map.get( key ) );
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
key만 출력하면 컬럼명만 출력됨
map.get(key); 출력하면 데이터가 출력됨
프로젝트를 새로 생성하여 문제풀기
사원명의 앞자리 일부만 입력하여 사원정보를 출력하는 mybatis 구문 완성
(empno, ename, sal, deptno)
/* EmpTO.java */
public class EmpTO {
private String empno;
private String ename;
private String sal;
private String deptno;
public String getEmpno() {
return empno;
}
public void setEmpno(String empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public String getDeptno() {
return deptno;
}
public void setDeptno(String deptno) {
this.deptno = deptno;
}
}
getter / setter 생성해줌
<!-- log4j.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%-5p](%-35c{1}:%-3L) %m%n" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="console"/>
</root>
</log4j:configuration>
console에 보여줌
<!-- myBatisConfig.xml -->
<?xml version= "1.0" encoding ="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="mariadb1">
<environment id="mariadb1">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3306/sample" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
<environment id="mariadb2">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="org.mariadb.jdbc.Driver" />
<property name="url" value="jdbc:mariadb://localhost:3306/project" />
<property name="username" value="project" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper.xml"/>
</mappers>
</configuration>
한가지만 사용할건데 나중을 위해 두가지 선언
<!-- mapper.xml -->
<?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.xml -->
<mapper namespace="mybatis" >
<select id="selectList" parameterType="String" resultType="EmpTO" >
select empno, ename, sal, deptno
from emp
where ename like concat( #{ename}, '%' );
</select>
</mapper>
데이터 조회할 sql문을 작성
/* MyBatisEx01.java */
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisEx01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
sqlSession = sqlSessionFactory.openSession();
System.out.println( "데이터베이스와 연결됨" );
List<EmpTO> lists = sqlSession.selectList( "selectList", "S" );
System.out.println( lists.size() + "개 검색" );
for(EmpTO to : lists ) {
System.out.print( to.getEmpno() + " " );
System.out.print( to.getEname() + " " );
System.out.print( to.getSal() + " " );
System.out.println( to.getDeptno() );
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
MyBatis 테이블 만들기
<!-- mapper.xml -->
<?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">
<!-- mapper2.xml -->
<mapper namespace="mybatis3" >
<update id="createtable1" parameterType="String">
${ value }
</update>
</mapper>
//MyBatisEx10.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class MyBatisEx12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
sqlSession = sqlSessionFactory.openSession(true);
System.out.println( "데이터베이스와 연결됨" );
String sql = "create table tbl1 (col1 varchar(10) )";
int result = sqlSession.update( "createtable1", sql );
System.out.println( "성공 : " + result );
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
비슷한 방법으로 만드는법
<!-- mapper.xml -->
<?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">
<!-- mapper2.xml -->
<mapper namespace="mybatis3" >
<update id="createtable1" parameterType="String">
${ value }
</update>
<update id="createtable2" parameterType="String">
create table ${ value }
( col varchar(10) )
</update>
</mapper>
// MyBatisEx01.java
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
public class MyBatisEx12 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String resource = "myBatisConfig.xml";
InputStream is = null;
SqlSession sqlSession = null;
try {
is = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
System.out.println( "설정이 성공적으로 호출됨" );
sqlSession = sqlSessionFactory.openSession(true);
System.out.println( "데이터베이스와 연결됨" );
// String sql = "create table tbl1 (col1 varchar(10) )";
// int result = sqlSession.update( "createtable1", sql );
int result = sqlSession.update( "createtable2", "tbl2" );
System.out.println( "성공 : " + result );
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println( "[에러] : " + e.getMessage() );
} finally {
if ( sqlSession != null ) sqlSession.close();
if ( is != null ) try { is.close(); } catch( IOException e ) {}
}
}
}
* Spring(MVC Model2) - 모델2를 쉽게 개발하려 제공하는 프레임워크
'🎧️ 강의듣기' 카테고리의 다른 글
Spring Framework (0) | 2021.08.05 |
---|---|
이클립스 Spring 설정하기 (0) | 2021.08.05 |
jQuery-ui accordion / datepicker / dialog (0) | 2021.07.15 |
jquery-ui (0) | 2021.07.14 |
jQuery 문법 (0) | 2021.07.13 |