상세 컨텐츠

본문 제목

Spring - MyBatis를 활용한 db 출력

03_Language

by 에스프리터 2018. 4. 3. 17:54

본문





늘은 Spring에서 MYBatis를 활용하여 Db를 출력하는 방법을 배우도록 하겠습니다.
파일 구조는 아래와 같이 되어 있습니다. 그리고 아래의 Github 주소에서 관련 파일 확인 가능합니다.




pack.business 패키지

** Main.java **
package pack.business;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ApplicationContext context =
                new ClassPathXmlApplicationContext("init.xml");
        
        ProcessInter inter =
                (ProcessInter)context.getBean("processImpl");
        inter.dataShow();

    }

}

** ProcessImpl.java **
package pack.business;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import pack.model.DaoInter;
import pack.model.SangpumDto;

@Service
public class ProcessImpl implements ProcessInter{
    @Autowired
    private DaoInter daoInter;
    
    @Override
    public void dataShow() {
        List<SangpumDto> list = daoInter.selectDataAll();
        
        for(SangpumDto sang:list) {
            System.out.println(sang.getCode() + " " +
                    sang.getSang() + " " +
                    sang.getSu() + " " +
                    sang.getDan());
            
        }
        
    }
    
}


** ProcessInter.java **
package pack.business;

public interface ProcessInter {
    void dataShow();
}



pack.model 패키지

** DaoImpl.java **
package pack.model;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import pack.resource.SqlMapConfig;

@Repository
public class DaoImpl implements DaoInter{
    private SqlSessionFactory factory = SqlMapConfig.getSqlSessionFactory();
    
    @Override
    public List<SangpumDto> selectDataAll(){
        SqlSession session = factory.openSession();
        List<SangpumDto> list = null;
        try {
            list = session.selectList("selectDataAll");
        } catch (Exception e) {
            System.out.println("selectDataAll err : " + e);
        }finally {
            if(session != null) session.close();
        }
        
        return list;
    }
}

** DaoInter.java **
package pack.model;

import java.util.List;

public interface DaoInter {
    List<SangpumDto> selectDataAll();
}


** SangpumDto.java **
package pack.model;

public class SangpumDto {
    private String code, sang, su, dan;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getSang() {
        return sang;
    }

    public void setSang(String sang) {
        this.sang = sang;
    }

    public String getSu() {
        return su;
    }

    public void setSu(String su) {
        this.su = su;
    }

    public String getDan() {
        return dan;
    }

    public void setDan(String dan) {
        this.dan = dan;
    }
    
    
    
}


pack.resource 패키지

** SqlMapConfig.xml **
package pack.resource;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Repository;

public class SqlMapConfig {
    public static SqlSessionFactory sessionFactory;
    
    static {
        String resource = "pack/resource/Configuration.xml";
        try {
            Reader reader = Resources.getResourceAsReader(resource);
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        } catch (Exception e) {
            System.out.println("SqlMapConfig err : " + e);
        }
    }
    
    public static SqlSessionFactory getSqlSessionFactory() {
        return sessionFactory;
    }
}



** DataMapper.xml **
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

<configuration>

<properties resource="pack/resource/db.properties" />
  <typeAliases>
    <typeAlias type="pack.model.SangpumDto" alias="dto"/>
</typeAliases>
<environments default="dev">
  <environment id="dev">
   <transactionManager type="JDBC" />
   <dataSource type="POOLED">
    <property name="driver" value="${driver}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
   </dataSource>
  </environment>
</environments>
<mappers>
  <mapper resource="pack/resource/DataMapper.xml" />
</mappers>
</configuration>


** DataMapper.xml **
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

<mapper namespace="dev">
<select id="selectDataAll" resultType="dto">
  select * from sangdata
</select>

</mapper>

** dbproperties **
driver=org.mariadb.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test
username=root

password=123

그 외

** pom.xml **
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.springframework.samples</groupId>
    <artifactId>espriter_app11_db_mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <properties>

        <!-- Generic properties -->
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

        <!-- Spring -->
        <spring-framework.version>4.3.3.RELEASE</spring-framework.version>

        <!-- Hibernate / JPA -->
        <hibernate.version>4.2.1.Final</hibernate.version>



        <!-- Logging -->
        <logback.version>1.0.13</logback.version>
        <slf4j.version>1.7.5</slf4j.version>

        <!-- Test -->
        <junit.version>4.11</junit.version>
    </properties>


    <dependencies>
        <!-- Spring and Transactions -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-framework.version}</version>
        </dependency>

        <!-- Mybatis -->
        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
        </dependency>

        <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
        </dependency>

        <!-- AOP -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.6</version>
        </dependency>
        
        <!-- RDBMS : MariaDb driver -->
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>2.2.3</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.0.0.RELEASE</version>
        </dependency>

        <!-- Logging with SLF4J & LogBack -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
            <scope>runtime</scope>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>


        <!-- Test Artifacts -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-framework.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
</project>


** readme.md **
공지사항
===================


안녕하세요. 에스프리터입니다.
해당 프로젝트에 대한 설명을 적기 위한 공간입니다.

----------



결과 이미지



본 포스팅은 KIC 캠퍼스에서 박영권 강사의 지도하에 공부하며 작성한 리포트입니다.
혹시 잘못된 내용이 있거나 문제 소지시 댓글 남겨주시면 조치하겠습니다.



태그

관련글 더보기

댓글 영역