티스토리 뷰

프로그래밍/Web

Mybatis & MySQL

국윤창 2018. 1. 29. 03:22

Mybatis

Mybatis는 JDBC로 처리하는 코드와 파라미터 설정 및 결과 매핑을 대신해주는 퍼시스턴스 프레임워크다. 동적 SQL, POJO 매핑 등의 기능을 제공한다.

Mybatis 설정

Spring boot에서 Mybatis를 이용해 MySQL을 연동하기 위해선 먼저 아래와 같이 Maven에 Dependency를 설정해줘야한다.

...

<!-- Mybatis-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.0</version>
</dependency>

<!-- Driver-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

...

Mybatis와 MySQL을 연동하기 위한 connector를 dependency로 추가했다. 이제 Database를 어떤 것을 사용할 지 property에 명시를 해야한다. 아래는 spring 프로젝트 생성 시 default로 있는 application.properties에 추가한 내용이다.

...

spring.db1.datasource.url=jdbc:mysql://localhost:3306/test_db
spring.db1.datasource.username=test_user
spring.db1.datasource.password=test_pw
spring.db1.datasource.driverClassName=com.mysql.jdbc.Driver

...

어떤 Database를 사용할 지 주소를 url에 명시하고, Database에 접근할 때 필요한 id, password를 명시해놨다. 그리고 mysql에 접근할 driver를 명시해놨다.

 

이제 configuration class에서 Datasource, SqlSession, Template Bean을 설정해줘야 한다. 우선 아래의 코드를 보자.

@Configuration
@MapperScan(
    basePackages="com.example.demo",
    sqlSessionFactoryRef = "mysqlSessionFactory",
    sqlSessionTemplateRef = "mysqlSessionTemplate")
public class DemoConfig {
    @Bean(name="mysqlDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.db1.datasource")
    public DataSource dbDataSource()
    {
        return DataSourceBuilder.create().build();
    }

    @Bean(name="mysqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mysqlDataSource")DataSource dataSource) throws Exception
    {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        sessionFactoryBean.setDataSource(dataSource);
        // annotation이 아닌 xml을 통한 mapping을 할거면 아래와 같이 사용
        //PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        //sessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mapper/abc.xml"));

        return sessionFactoryBean.getObject();
    }

    @Bean(name="mysqlSessionTemplate")
    @Primary
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception
    {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

@MapperScan annotation을 명시해 준 class는 basePackages로 지정한 곳에 존재하는 @Mapper로 명시된 interface를 스캔한다. sqlSessionFactoryRef, sqlSessionTemplateRef 속성은 Database를 여러개 연결할 때 구분해주기 위한 속성이다. 두 개 이상의 MapperScan class 사용 시 명시를 안하면 오류가 난다. @Primary는 Database가 두 개 이상 있을 때 어떤 Database를 첫 번째로 사용할 것인지 지정하는 annotation이다.

 

이제 basePackages 속성에 지정한 package에 Mapper interface를 만들어보자.

@Mapper
public interface userMapper {
    @Select("SELECT * FROM user WHERE uid > #{uidNumber}")
    List<userDTO> getUsersOverUID(@Param("uidNumber")int uidNumber);
}

Mapper는 반드시 interface로 구현해야 한다. @Select annotation을 이용해 user라는 이름의 table에서 uid 값이 매개변수 uidNumber보다 큰 데이터를 userDTO의 List로 반환하고 있다. 저번 포스팅에서 DTO에 관해서 간단히 적었는데, Database를 이용할 때 값을 받아올 class이다. userDTO는 아래 코드처럼 구현된다.

public class userDTO {
    private BigInteger uid;
    private String id;
    private String pw;
    private Timestamp date;
    private Timestamp modDate;
    private String nickname;

    // 아래에 public으로 getter setter 구현 (길어서 생략)
}

위와 같이 data와 getter, setter로만 돼있는 순수 자바 객체(POJO)에 query문 결과가 담겨 List로 반환되는 것이다. 이것을 이용하려면 아래 DAO 클래스처럼 사용하면 된다.

@Repository("userDAO")
public class userDAO {
    @Autowired
    @Qualifier("userMapper")
    private userMapper userMapper;

    public List<String> getUserIDs()
    {
        return userMapper.getUsersOverUID(0)
                .stream()
                .map(user->user.getId())
                .collect(Collectors.toList());
    }
}

위처럼 @Autowired annotation으로 userMapper를 주입받아서 query문을 사용할 수 있다. getUserIDs 함수 내부의 복잡해보이는 호출은 C#의 linq와 비슷한 역할을 하는 것이니 참고하자.

 

DAO를 Service나 Controller에서 주입받아서 얻어온 내용을 아래 그림 1처럼 테스트 view에 띄워볼 수 있다. 이 내용은 저번 포스팅과 겹치므로 생략하겠다.

결과 화면
[그림 1] query 결과 출력

 


참조

Mybatis 예제

https://dayone.me/1SlXzM0

 

Spring Boot Mybatis 설정

Spring Boot + Spring Batch 기준으로 작성 되었음 ㅎㅎ Mybatis의 기본 구조는 다음과 같다. - Mybatis는 SqlSession이라는 자바 인터페이스를 이용해서 명령어 실행, Mapper 획득, 트랜잭션 관리 등을 맡게 된다. - SqlSession은 SqlSessionFactory를 통해서 생성된다. - Mybati...

dayone.me

blogId=islove8587&logNo=220989983084&proxyReferer=https%3A%2F%2Fwww.google.co.kr%2F

 

SpringBoot MVC 마이바티스(myBatis) 연동

1. Spring MVC 마이바티스(myBatis) 연동 포스트 참조- 마이바티스(myBatis) 연동하기- 마이바티스(m...

blog.naver.com

https://blog.naver.com/PostView.nhn?

불러오는 중입니다...

https://gs.saro.me/#!m=elec&jn=778

 

가리사니

가리사니 개발자공간

gs.saro.me

공식 레퍼런스

http://www.mybatis.org/spring/ko/getting-started.html

 

mybatis-spring – 마이바티스 스프링 연동모듈 | 시작하기

시작하기 이 장은 마이바티스 스프링 연동모듈을 설치하고 셋팅하는 방법에 대해 간단히 보여준다. 그리고 트랜잭션을 사용하는 간단한 애플리케이션을 만드는 방법까지 다룰 것이다. 설치 마이바티스 스프링 연동모듈을 사용하기 위해서, 클래스패스에 mybatis-spring-2.0.3.jar를 포함시켜야 한다. 메이븐을 사용하고 있다면 pom.xml에 다음처럼 의존성을 추가하면 된다. org.mybatis mybatis-spring 2.0.3 빠른 설정 마이바티스를

mybatis.org

Mybatis 퀵 가이드

http://www.baeldung.com/mybatis

 

Quick Guide to MyBatis | Baeldung

Learn about MyBatis, an open source persistence framework which simplifies the implementation of database access.

www.baeldung.com

MySQL & jdbc 연결 관련

http://razorsql.com/docs/help_mysql.html

 

MySQL JDBC Driver and URL Information

Listed below are connection examples for MySQL: MySQL Connector/J Driver DRIVER CLASS: com.mysql.jdbc.Driver DRIVER LOCATION: Simply provide the location of the jar file containing the MySQL JDBC Drivers. These drivers can be obtained from MySQL. See the M

razorsql.com

Database 두개 이상 사용 시 주의사항

http://mazdah.tistory.com/632

 

[Spring 3.1.1] datasource 2개 사용하기.

Spirng 3.1.1 + MyBatis + jQuery로 웹 사이트를 구현하고 있다. 그런데 현재 시스템에서 서로 다른 2개의 DB를 사용을 하고 있는 상태이다. 물론 한쪽 DB로 접속해서 소유권을 명시적으로 기술해서 타 DB의 테이..

mazdah.tistory.com

 

'프로그래밍 > Web' 카테고리의 다른 글

게시판 만들기  (0) 2018.02.18
Spring과 Cookie & Session  (0) 2018.02.05
DAO, DTO, Service  (4) 2018.01.28
Annotation과 Bean  (2) 2018.01.27
Spring Bean  (2) 2018.01.27
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
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
글 보관함