일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- String
- for문
- 형변환
- jdbc
- SQL
- 자료구조
- JavaScript
- DB
- JCF
- jsp
- extends
- 자바
- jar
- java
- html
- regex
- 정규화표현식
- mybatis
- Set
- iBATIS
- scope
- controller
- interface
- 환경설정
- Selector
- jquery
- 알고리즘
- 자바스크립트
- 개선
- 참조타입
- Today
- Total
프로그래밍공부노트
Day 42 - iBatis 본문
IBatis vs myBatis
1) IBatis 와 myBatis의 차이는 버전의 차이다.
지금은 모두 myBatis라고 통칭해서 이야기 해달라고 한다.
2) ORM(Object Relation Mapping)은 아니다
- JPA(Java Application Persistence), Hibernate ...등등 ORM이다
- Java의 객체와 Database의 Entity를 1:1로 매핑하여 사용하는 것을 ORM이라고 한다.
3) 하지만 myBatis는 JDBC를 관리하기 편하도록 사용하기 위함이고 Persistence Layer라고 한다
myBatis는 총 3가지가 필요하다
그림
4) profile : 사용되는 db의 정보가 여러개인 경우 Maven을 통해서 선택 build할 수 있도록 함
5) xml을 통해서 쿼리를 갖고 있는 xml mapper가 있음
6) java로 되어있는 Interface mapper가 있음
1) 라이브러리 : oracle(OJDBC6.jar), iBatis(2.5).jar
2) 환경설정 파일 생성 : Configuration.xml
- 만약에 설정 값(DB의 설정 값)이 외부에 properties파일로 되어 있다면 사용하기 위해서 연결
<properties/>
- iBatis에서 추가적으로 필요한 설정
<settings>
- S(sqlMapConfig)
- S(settings)
- T(transcationgManager) type="JDBC" D(dataSource) type="Simple" P(property) name="", value=""순으로 작성하면 된다. 만약 propertiy에 있는 값을 사용하고 싶다면 value=${property의 해당명}
아니다 그냥 내가 원하는 값 사용하겠다 value="oracle.jdbc.driver.OracleDriver"
3) 쿼리문을 가지고 있는 xml을 연결 : <sqlMap>에 위치를 걸어주면 연결된다.
**xml 이란?
- wel-formed, validate 하다
- 잘 만들어졌다(<시작></닫힘>으로 잘 구성되어 있다)
- valide하다(구성의 설정이 잘 되어 있다) : 즉 마음대로 구성할 수 없고 규칙에 의해서 사용한다.
=>DTD를 선언함으로써 필요한 규칙을 가진 xml파일을 만들어낼 수 있다
iBatis 환경 설정
useStatementNamespaces="true" : 개발자가 mapper.xml에 각각 이름을 부여하고 그걸 사용하겠다
iBatis 작성했던 JDBC와 연결하기
세팅이 우선 다 끝나야 한다.
내가 지금 배우고 있는 상황에서 확인해야 하는 것은 일단은 maven project 생성하고 다 세팅한다음에 플러그인 설정하고 버전 설정하고 그 다음에 pom.xml에 repository랑 dependencies 확인할 것(oracle, log4j, myBaits)
확인을 마치면 properties 작성할 것 두개 db, log4j 작성하면 된다.
작성하신 다음에 Configuration.xml을 작성한다. map.config로 생성하는 것 잊지 말고 작성방식은 SSTDP였다.
<sqlMapConfig>
<properites/>
<settings/>
<transcationManager/> 요안에 <dataSource> 요안에 <property>
그리고 마지막에 쿼리를 가지고 있는 xml을 mapping한다 연결!
daoSupport
그리고 daoSupport 만들어준다
이친구는 single-ton으로 구성되어 있고 멤버필드로 sqlMapClient를 선언
static 영역에 String 타입의 path를 가지고 있다.
이 path는 configuration.xml이 있는 위치를 입력해준다.
Reader를 통해서 path를 받아 읽어서 담아주고
sqlMapClientBuilder를 통해 Reader를 Argument로 받아서 sqlMapClient에 담아준다.
그리고 Reader는 IO 객체이기 때문에 닫아준다.
package com.min.edu.ibatis;
import java.io.IOException;
import java.io.Reader;
import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
public class SqlDaoSupport {
private static SqlMapClient sqlMapClient;
static {
String path ="com/min/edu/ibatis/Configuration.xml";
//iBatis 객체의 IO를 통해 읽어서 넣어줌
try {
Reader reader = Resources.getResourceAsReader(path);
sqlMapClient = SqlMapClientBuilder.buildSqlMapClient(reader);
System.out.println("sqlMapClient 객체 성공");
reader.close();
} catch (IOException e) {
System.out.println("sqlMapClient 객체 실패");
e.printStackTrace();
}
}
public static SqlMapClient getSqlMapClient() {
return sqlMapClient;
}
}
쿼리를 준비할 xml에 작성해야할 것
쿼리를 준비하기 위한 xml을 생생한다. 얘는 mapconfig가 아니라 map으로 설정하여 생성해야한다.
namespace먼저 작성해라 이것은 interface 혹은 구현한 impl의 위치를 작성해주면 된다
그리고 쿼리 작성
일단 오늘은 select를 해서 <select></select> 여기 사이에 쿼리를 작성하면되고
id와 parameterClass resultClass 속성을 부여해준다
id(호출), parameterClass(입력받는 argument의 객체 혹은 타입), resultClass(쿼리가 실행된 후 반환되는 값을 담는 객체)
id는 쿼리를 실행할때 가져갈 id라는 것을 생각하자 parameterClass는 없으면 설정 안해도 된다.
iBatis 사용할때 namespace.쿼리id 방식으로 호출
typeAlias 사용하는 DTO/VO 객체의 위치를 찾기가 힘들다 한번 선언해서 변수처럼 사용가능한 TAG
쿼리문을 작성하기전에 테스트를 진행한다. 그리고 조건절에 들어가는 값은 binding을 해야한다
이때 ##으로 묶어주면 된다. 그 사이에 들어가는 변수명은 개발자가 알아서 작성하면 된다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd" >
<sqlMap namespace="com.min.edu.ibatis.StarMemberSelectDaoImpl">
<typeAlias alias="sDto" type="com.min.edu.dto.StarMemberDto"/>
<!-- 리스트로 받기 -->
<select id="getAllUserStatus" resultClass="sDto" >
SELECT * FROM STARMEMEBER
</select>
<select id="getAllUser" resultClass="sDto">
SELECT * FROM STARMEMBER
</select>
<update id="updateAuthUser" parameterClass="sDto">
UPDATE STARMEMBER SET NAME=#name# WHERE ID=#id#
</update>
<select id="getUser" parameterClass="sDto" resultClass="sDto">
SELECT * FROM STARMEMBER WHERE ENABLE=#y#;
</select>
<select id="getLogin" parameterClass="sDto" resultClass="sDto">
SELECT NAME, ADDRESS, PHONE, EMAIL, ENABLE, ROLE FROM STARMEMBER WHERE ID=#id# AND PASSWORD=#password#
</select>
</sqlMap>
select만 연습
Impl
쿼리를 실행시키기 위해 Interface 구현한 class 생성한다(interface를 implements 한 클래스)
여기에 sqlDaoSupport를 통해서 sqlMapClient를 get해와서 manager에 담아준다.
log도 찍어줄 준비하고 NS도 xml에서 namespace 그대로 가져와라 /말고 .으로 변경해라
그리고 구현해야할 메소드에 이제 쿼리문 실행할 수 있도록 해준다.
반환 타입에 맞춰서 초기값? 설정해주고 반환값 설정해준다.
그리고 실행해주면 된다.
list라면 queryForList(NS+"쿼리실행할 ID)
object라면 queryForObject(NS+"쿼리실행할 ID)
map이라면 qeuryForMap(NS+"쿼리실행할 ID)
작성하고 초기값 설정해준 것에 넣어주고 반환끝
package com.min.edu.dao;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.min.edu.dto.StarMemberDto;
public class StarMemberiBatisDao_Impl implements IStarMemberDao {
private SqlMapClient manager = SqlDaoSupport.getSqlMapClient();
private Logger log = Logger.getLogger(this.getClass());
private final String NS ="com.min.edu.ibatis.StarMemberSelectDaoImpl.";
@SuppressWarnings("unchecked")
@Override
public List<StarMemberDto> getAllUserStatus() {
List<StarMemberDto> lists = null;
try {
lists = manager.queryForList(NS+"getAllUserStatus");
log.info("getAllUserStatus");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lists;
}
@SuppressWarnings("unchecked")
@Override
public List<StarMemberDto> getAllUser() {
List<StarMemberDto> lists = null;
try {
lists = manager.queryForList(NS+"getAllUser");
log.info("getAllUser");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return lists;
}
@Override
public StarMemberDto getLogin(String id, String password) {
StarMemberDto dto = new StarMemberDto();
dto.setId(id);
dto.setPassword(password);
try {
dto = (StarMemberDto)manager.queryForObject(NS+"getLogin");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dto;
}
@Override
public StarMemberDto getUser(int seq) {
StarMemberDto dto = null;
try {
dto = (StarMemberDto) manager.queryForObject(NS+"getUser", seq);
log.info("getUser");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return dto;
package com.min.edu.test;
import java.util.List;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.min.edu.dao.IStarMemberDao;
import com.min.edu.dao.SqlDaoSupport;
import com.min.edu.dao.StarMemberDao_Impl;
import com.min.edu.dto.StarMemberDto;
public class StarMemberIbatis_Main {
public static void main(String[] args) {
//1.log4j test
// Log4j log = new Log4j();
// log.userLogger();
//
// SqlMapClient manager = SqlDaoSupport.getSqlMapClient();
// System.out.println(manager.getClass());
IStarMemberDao dao = new StarMemberDao_Impl();
// List<StarMemberDto> lists = dao.getAllUserStatus();
// System.out.println(lists);
// List<StarMemberDto> lists = dao.getAllUser();
// System.out.println(lists);
// StarMemberDto dto = dao.getUser(8);
// System.out.println(dto);
//
StarMemberDto dto = dao.getLogin("m001", "m001");
System.out.println(dto);
}
}
나온긴 하는데 제대로 나오는건지는 모르겠다..........
'iBatis' 카테고리의 다른 글
Day 44 - iBatis(Dynamic Query) (0) | 2021.04.16 |
---|---|
Day 43 - iBatis (selectKey , Binding, DynamicQuery) (0) | 2021.04.15 |
Day 41 - iBatis(환경설정, 테스트) (0) | 2021.04.12 |