Spring Boot 게시판 만들기 2 : DB 연동 및 Mybatis 설정

Spring Boot - ver 2.1.8

Gradle

Java - ver 1.8

 

application.properties

내에 datasource 관련 설정값 선언

1
2
3
4
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://ip:3306/~?useSSL=false&serverTimezone=UTC
spring.datasource.username=id
spring.datasource.password=pw
cs

 

스프링부트 앱을 구동시키는 main 메소드 내의 @SpringBootApplication 을 들어가보면 @EnableAutoConfiguration 어노테이션이 존재.

해당 어노테이션이  프로젝트 내 Bean 들의 DI 주입을 자동으로 설정해준단다.

(Spring Framework 프로젝트의 web.xml 파일 내에 context.xml 를 매핑해주는 과정을 직접 하지 않아도 된다고 한다)

이 이상 자세히 파기엔 내공의 한계가 있어 일단 나중에 더 공부해보자..

 

위와 같이 프로퍼티에 datasource 관련 설정값만 선언해주면

아래와 같은 코드와 같다고 보면 된다.

1
2
3
4
5
6
7
8
9
10
    @Bean
    public DataSource customDataSource() {
 
        return DataSourceBuilder.create()
                                .url("jdbc:mysql://ip:3306/!?useSSL=false&serverTimezone=UTC")
                                .driverClassName("com.mysql.cj.jdbc.Driver")
                                .username("id")
                                .password("pw")
                                .build();
    }
cs

 

다음으로,

SqlSessionFactory 와 SqlSessionTemplate 설정.

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
package com.jpp.main.config;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(value= {"com.jpp.main.mapper"})
@EnableTransactionManagement
public class MybatisConfig {
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)throws Exception{
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            
            Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml");
            
            sessionFactory.setMapperLocations(res);
            
            return sessionFactory.getObject();
    }
 
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
 
cs

위와 같이 datasource 관련 설정을 application.properties 에 설정하고,

mybatis 관련 설정은 java config 로 설정할 수 있다. (mybatis 는 application.properties 에 설정 불가)

application.properties 에 설정 가능한 값들은 여기를 참고

 

 datasource도 application.properties 대신 java config 로 설정하고 싶다면 아래와 같이 datasource 를 @Bean 으로 설정해주자.

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
package com.jpp.main.config;
 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@MapperScan(value= {"com.jpp.main.mapper"})
@EnableTransactionManagement
public class MybatisConfig {
    
    @Bean
    public DataSource customDataSource() {
        return DataSourceBuilder.create()
                                .url("jdbc:mysql://ip:3306/~?useSSL=false&serverTimezone=UTC")
                                .driverClassName("com.mysql.cj.jdbc.Driver")
                                .username("id")
                                .password("pw")
                                .build();
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)throws Exception{
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            
            Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml");
            
            sessionFactory.setMapperLocations(res);
            
            return sessionFactory.getObject();
    }
 
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
 
cs

17 Line : @MapperScan : com.jpp.main.mapper 경로 밑에 있는 mapper Interface 를 스캔하여 빈으로 등록 (mapper Interface 대신 DAO를 사용할 경우 필요 없음)

36 Line : getResources("classpath:mapper/*Mapper.xml");

~Mapper.xml 파일명 기준 모든 sql mapper 를 sqlSessionFactory에 등록

 

 

[mainMapper.xml]

간단한 select 쿼리를 작성하여 Mapper를 작성해준다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
 
<mapper namespace="com.jpp.main.mapper.MainMapper">
 
    <select id="getUserList" resultType="com.jpp.main.vo.UserVO">
        select empno as no, emp_nm as name 
        from emp_info
        limit 10
    </select>
 
</mapper>
 
 
cs

 

* Mapper Interface 사용 vs DAO 사용

1) DAO 사용시

1-1) MainDao

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.jpp.main.dao;
 
import java.util.List;
 
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.jpp.main.vo.UserVO;
 
@Repository
public class MainDAO {
    
   @Resource
    private SqlSessionTemplate sqlSessionTemplate;
    
    private static final String MAPPER_NM = "com.jpp.main.mapper.MainMapper.";
    
    public List<UserVO> getUserList(){
        return sqlSessionTemplate.selectList(MAPPER_NM+"getUserList");
    }
}
 
cs

1-2) MainService

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
package com.jpp.main.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.jpp.main.dao.MainDAO;
import com.jpp.main.mapper.MainMapper;
import com.jpp.main.vo.UserVO;
 
@Service
public class MainService {
    @Autowired
    private MainDAO mainDao;
    
    public List<UserVO> getUserList() throws Exception {
        return mainDao.getUserList();
    }
}
 
cs

 

 

2) mapper Interface 사용시

2-1) MainMapper

1
2
3
4
5
6
7
8
9
10
11
package com.jpp.main.mapper;
 
import java.util.List;
 
import com.jpp.main.vo.UserVO;
 
public interface MainMapper {
    
    public List<UserVO> getUserList() throws Exception;
}
 
cs

 

2-2) MainService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.jpp.main.service;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.jpp.main.dao.MainDAO;
import com.jpp.main.mapper.MainMapper;
import com.jpp.main.vo.UserVO;
 
@Service
public class MainService {
 
    @Autowired
    private MainMapper mainMapper;
    
    public List<UserVO> getUserList() throws Exception {
        
        return mainMapper.getUserList();
    }
}
 
cs

 

 

 

반응형

+ Recent posts