관리 메뉴

피터의 개발이야기

[Spring] Mybatis 연동 본문

Programming/Spring

[Spring] Mybatis 연동

기록하는 백앤드개발자 2021. 1. 3. 08:00
반응형

 오늘은 Mybatis연동을 정리합니다.

gradle 설정

	//DataBase Mybatis mysql
	implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.0.0'
	compile group: 'org.mybatis', name: 'mybatis', version: '3.4.6'
	compile group: 'org.mybatis', name: 'mybatis-typehandlers-jsr310', version: '1.0.2'
	compile group: 'org.mybatis', name: 'mybatis-spring', version: '1.3.2'
	compile group: 'mysql', name: 'mysql-connector-java'

 

DDBConnectionConfig

@Configuration
@Slf4j
public class DBConnectionConfig {
    @Value("${spring.datasource.url}")
    private String dbUrl;
    @Value("${spring.datasource.username}")
    private String dbUsername;
    @Value("${spring.datasource.password}")
    private String dbPassword;
    @Value("${spring.datasource.classname}")
    private String dbClassName;

    @Bean
    public DataSource dataSource() {
        final HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setUsername(dbUsername);
        hikariConfig.setPassword(dbPassword);
        hikariConfig.addDataSourceProperty("url", dbUrl);
        hikariConfig.setDataSourceClassName(dbClassName);
        hikariConfig.setLeakDetectionThreshold(2000);
        hikariConfig.setMaximumPoolSize(30);
        hikariConfig.setPoolName("peterPool");

        final HikariDataSource dataSources = new HikariDataSource(hikariConfig);
        return dataSources;
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*Mapper.xml"));
        sessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:config/mybatis-config.xml"));
        sessionFactory.setVfs(SpringBootVFS.class);

        return sessionFactory.getObject();
    }
}

 

Application.properties

############
# Database #
############
spring.datasource.classname=com.mysql.cj.jdbc.MysqlDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC&allowMultiQueries=true
spring.datasource.username=username
spring.datasource.password=password

# mybatis 매핑 type을 짧게 쓰기 위한 설정
mybatis.type-aliases-package=com.peterica.swagger.model

 

Controller

    @GetMapping("/dbTest")
    @ApiOperation(httpMethod = "GET", value = "Mybatis Test", notes = "Mybatis Test")
    public List<String> dbTest(){
        return testService.getTest();
    }

 

Service

@Service
@RequiredArgsConstructor
public class TestService {

    private final TestRepository testRepository;

    public List<String> getTest(){
        return testRepository.getTestList();
    }
}

 

Repository

@Repository
@RequiredArgsConstructor
public class TestRepository {

    private final SqlSession sqlSession;

    public List<String> getTestList(){
        return sqlSession.selectList("test.getTest");

    }
}

 

Mapper

<?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="test">

    <select id="getTest" resultType="String">
        select memo
        from test
    </select>

</mapper>

 

Mysql

create table test
(
    memo varchar(12)  null
)
    charset = utf8;

insert into test (memo) value ('test');

 

웹 호출

데이터 조회 성공.

반응형
Comments