반응형
MyBatis
Spring Framework에서 제공하는 JDBC 라이브러리를 보다 쉽게 작업할 수 있도록 만든 라이브러리입니다.
Mapper의 역할을 확장하여 쿼리문 작성을 모두 Mapper에서 할 수 있도록 지원합니다.
Spring Framework의 대표적 JDBC 라이브러리입니다.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>kr.co.softcampus</groupId>
<artifactId>MyBatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- xml에서 사용할 속성들 -->
<properties>
<!-- 자바 버전 -->
<java-version>1.8</java-version>
<!-- 스프링 버전 -->
<org.springframework-version>5.1.9.RELEASE</org.springframework-version>
<!--<org.springframework-version>4.3.25.RELEASE</org.springframework-version> -->
<org.slf4j-version>1.7.26</org.slf4j-version>
<ch.qos.logback-version>1.2.3</ch.qos.logback-version>
<javax.annotation-version>1.3.2</javax.annotation-version>
<org.aspectj-version>1.9.4</org.aspectj-version>
<com.oracle-version>11.2.0.3</com.oracle-version>
<org.apache.commons-version>2.7.0</org.apache.commons-version>
<org.mybatis-version>3.5.2</org.mybatis-version>
</properties>
<!-- Repository 정보 -->
<repositories>
<repository>
<id>oracle</id>
<name>ORACLE JDBC Repository</name>
<url>http://code.lds.org/nexus/content/groups/main-repo</url>
</repository>
</repositories>
<!-- 프로젝트에서 사용할 라이브러리 정보 -->
<dependencies>
<!-- spring context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- slf4j -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<!-- logback -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${ch.qos.logback-version}</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>${javax.annotation-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- oracle jdbc -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>${com.oracle-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${org.apache.commons-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${org.mybatis-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
</dependencies>
</project>
JdbcBean.java
package kr.co.softcampus.beans;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class JdbcBean {
private int int_data;
private String str_data;
public int getInt_data() {
return int_data;
}
public void setInt_data(int int_data) {
this.int_data = int_data;
}
public String getStr_data() {
return str_data;
}
public void setStr_data(String str_data) {
this.str_data = str_data;
}
}
BeanConfigClass.java
package kr.co.softcampus.config;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import kr.co.softcampus.mapper.MapperInterface;
@Configuration
@ComponentScan(basePackages = "kr.co.softcampus.beans")
public class BeanConfigClass {
// data source
@Bean
public BasicDataSource dataSource() {
BasicDataSource source = new BasicDataSource();
source.setDriverClassName("oracle.jdbc.OracleDriver");
source.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
source.setUsername("scott");
source.setPassword("1234");
return source;
}
// SqlSessionFactory : jdbc를 처리하는 객체
@Bean
public SqlSessionFactory factory(BasicDataSource source) throws Exception{
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(source);
SqlSessionFactory factory = factoryBean.getObject();
return factory;
}
// Mapper
@Bean
public MapperFactoryBean<MapperInterface> test_mapper(SqlSessionFactory factory) throws Exception{
MapperFactoryBean<MapperInterface> factoryBean = new MapperFactoryBean<MapperInterface>(MapperInterface.class);
factoryBean.setSqlSessionFactory(factory);
return factoryBean;
}
}
MapperInterface.java
package kr.co.softcampus.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import kr.co.softcampus.beans.JdbcBean;
public interface MapperInterface {
/*
@Results({
@Result(column = "int_data", property = "int_data"),
@Result(column = "str_data", property = "str_data")
})
*/
@Select("select int_data, str_data from jdbc_table")
List<JdbcBean> select_data();
@Insert("insert into jdbc_table (int_data, str_data) values (#{int_data}, #{str_data})")
void insert_data(JdbcBean bean);
@Update("update jdbc_table set str_data = #{str_data} where int_data = #{int_data}")
void update_data(JdbcBean bean);
@Delete("delete from jdbc_table where int_data = #{abc}")
void delete_data(int int_data);
}
MainClass.java
package kr.co.softcampus.main;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import kr.co.softcampus.beans.JdbcBean;
import kr.co.softcampus.config.BeanConfigClass;
import kr.co.softcampus.mapper.MapperInterface;
public class MainClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(BeanConfigClass.class);
MapperInterface mapper = ctx.getBean("test_mapper", MapperInterface.class);
// insert
// JdbcBean bean2 = new JdbcBean();
// bean2.setInt_data(100);
// bean2.setStr_data("문자열100");
// mapper.insert_data(bean2);
//
// JdbcBean bean3 = new JdbcBean();
// bean3.setInt_data(200);
// bean3.setStr_data("문자열200");
// mapper.insert_data(bean3);
// update
// JdbcBean bean4 = new JdbcBean();
// bean4.setInt_data(100);
// bean4.setStr_data("문자열300");
// mapper.update_data(bean4);
// delete
mapper.delete_data(100);
// select
List<JdbcBean> list1 = mapper.select_data();
for(JdbcBean bean1 : list1) {
System.out.printf("int_data : %d\n", bean1.getInt_data());
System.out.printf("str_data : %s\n", bean1.getStr_data());
System.out.println("--------------------------------------");
}
ctx.close();
}
}
정리
JDBC를 활용하기보다 MyBatis가 훨씬 사용하기 편리한 이유에 대해 알 수 있었습니다. 우선, 필드명과 이름을 맞춰주기만 하면, 자동으로 매핑이 되기 때문에, 관리가 더 수월하고 개발하기에도 더 수월하다는 것을 알 수 있었습니다.
좀 더 MyBatis에 동작 원리에 대해, 가볍게 이해해를 해보고, 다음 프로젝트에는 좀 더 주도적으로 활용해볼 계획입니다. Hibernate와는 달리 필드 기준으로 매핑이 되기 때문에 좋은 장점이라 생각하고, 국내 개발자분들도 Hibernate보다 MyBatis가 더 익숙하신 분들이 많은 것 같습니다.
다만 해외에서는 Hibernate를 많이 쓴다는 이야기를 본터라, 앞으로 어떤 라이브러리를 주로 사용할지에 대해서는 좀 더 고민해봐야할 것 같습니다.
MyBatis 설정과 방법에 대해서는 아래 강좌에서 구체적인 내용을 확인할 수 있습니다.
https://www.udemy.com/course/sooftcampus-sfb/
반응형
'SW > Java' 카테고리의 다른 글
Java : Java 개념, 유형, 개요, 설명, 종류 (0) | 2023.02.08 |
---|---|
Java : Spring Boot : 네이버 아이디로 로그인 : 예제, 구현 (0) | 2020.08.24 |
Java : Spring : JDBC : 개념, 사용, 방법, 예제, 구현 (0) | 2020.06.15 |
Java : Spring :AspectJ 어노테이션 : 개념, 사용, 방법, 예제, 구현 (0) | 2020.06.14 |
Java : Spring : Execution 명시자 : 종류,개념, 사용 방법, 예제, 구현 (0) | 2020.06.13 |