본문 바로가기
Back-end/JAVA

[JAVA] Mapper를 만들어보자 (1) - XML읽기

by 허도치 2020. 11. 18.
서론

  SQLite를 이용해서 DB를 다루다가 String에 SQL을 작성하는 것이 좀 불편했다. 그래서, mybatis나 ibatis처럼 XML 파일에 SQL을 작성하고 이를 읽어서 사용하고 싶어졌다. 그래서, 이번 포스트에서는 XML파일에 작성된 SQL을 읽어오는 방법에 대해서 다루어 보도록 하겠다.

 

 

 

개발환경
1. JAVA 버전

  - jdk-11.0.9

 

2. POM.xml
1
2
3
4
5
<dependency>
  <groupId>jdom</groupId>
  <artifactId>jdom</artifactId>
  <version>1.0</version>
</dependency>
cs

 

 

 

소스코드
1. MyMapper.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<mapper>
 
  <sql id="selectDateTime">
    SELECT strftime('%Y-%m-%d %H:%M:%S', datetime('now')) AS DATE_TIME
         , #{testValue} AS TEST_VALUE 
  </sql>
  
  <sql id="selectDate">
    SELECT strftime('%Y-%m-%d', datetime('now')) AS DATE_TIME
         , #{testValue} AS TEST_VALUE_A 
         , ${testValue} AS TEST_VALUE_B
  </sql>
  
</mapper>
cs

 

2. Mapper.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.dochi.db.ex.maaper;
 
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
 
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
 
public class Mapper {
    // 변수 설정
    //   - XML Child 객체 변수
    private Element element = null;
    
    // 생성자
    //   - Element를 저장
    public Mapper(Element element) {
        this.element = element;
    }
    
    // XML 탐색기
    //   - id가 'attrValue'인 sql 조회
    public String getSQL(String attrValue) {
        return getChild("sql""id", attrValue).getText();
    }
    
    //   - 속성명, 속성값으로 Child 탐색
    public Mapper getChild(String attrName, String attrValue) {
        return getChild(null, attrName, attrValue);
    }
 
    //   - 이름, 속성명, 속성값으로 Child 탐색
    public Mapper getChild(String name, String attrName, String attrValue) {
        List<?> children = null;
        
        if( name != null ) {
            children = this.element.getChildren(name);
        } else {
            children = this.element.getChildren();
        }
        
        Iterator<?> iter = children.iterator();
        while(iter.hasNext()) {
            Element element = (Element) iter.next(); 
            String elementAttrValue = element.getAttributeValue(attrName);
            
            if( elementAttrValue != null && elementAttrValue.equalsIgnoreCase(attrValue) ) {
                return new Mapper(element);
            }
        }
        
        return null;
    }
    
    public String getText() {
        return this.element.getText();
    }
    public List<?> getChildren() {
        return this.element.getChildren();
    }
    public List<?> getChildren(String name) {
        return this.element.getChildren(name);
    }
    public String getAttributeValue(String attrName) {
        return this.element.getAttributeValue(attrName);
    }
    public String getAttributeValue(String attrName, String defaultValue) {
        return this.element.getAttributeValue(attrName, defaultValue);
    }
    
    public static void main(String[] args) throws JDOMException, IOException {
 
        // 상수설정
        //   - Mapper 파일명
        final String XML_FILE_NAME = "src/main/java/com/dochi/db/ex/maaper/MyMapper.xml";
 
        // 변수설정
        //   - XML 변수
        SAXBuilder builder = new SAXBuilder();
        Document document = builder.build(XML_FILE_NAME);
        Element rootElement = document.getRootElement();
        
        //   - Mapper 객체 변수
        Mapper mapper = new Mapper(rootElement);
        
        //   - SQL 탐색
        String sql = mapper.getSQL("selectDateTime");
        
        System.out.println( sql );
    }
}
cs

 

 

 

실행결과

[ XML에서 'selectDateTime' SQL을 조회 ]

 

 

 

마치며

  이렇게 아주 간단하게(?) XML 파일에서 특정 SQL을 읽어오는 Mapper 클래스를 만들어 보았다. SQL을 살펴보면 '#{testValue}'가 눈에 들어올 것이다. 이 부분은 mybatis나 ibatis처럼 변수를 받아서 치환하려고 미리 넣어둔 것이다.

 

  다음 포스트에서 이 부분에 대해서 다루어 보도록 하겠다.

 

댓글