Notice
Recent Posts
Recent Comments
Link
«   2025/06   »
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
Archives
Today
Total
관리 메뉴

J.one_DevNote

{Spring Boot} - Mybatis 시작하기 본문

Spring Boot

{Spring Boot} - Mybatis 시작하기

중엔 2022. 6. 20. 13:24

방법 1. java config를 이용한 연결

1. maven dependency 설정

<dependency>
	<groupId>org.mybatis.spring.boot</groupId>
	<artifactId>mybatis-spring-boot-starter</artifactId>
	<version>2.2.0</version>
</dependency>

2. Java Config파일을 생성해 DB연결및 Mybatis연결 세팅을 해준다.

-sqlSessionFactory 메소드에서 mapper파일을 읽어드릴 범위 지정 

@Configuration
@MapperScan(value= {"com.ex.toypj.mapper"})
@EnableTransactionManagement
public class MyBatisConfig {
    @Bean
    public DataSource customDataSource() {
        return DataSourceBuilder.create()
                                .url("jdbc:mariadb://localhost:3306/DBName")
                                .driverClassName("org.mariadb.jdbc.Driver")
                                .username(ID)
                                .password(PASSWORD)
                                .build();
    }
	
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource)throws Exception{
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            
            Resource[] res = new PathMatchingResourcePatternResolver().getResources("classpath:/mappers/*.xml");
            
            sessionFactory.setMapperLocations(res);
            
            return sessionFactory.getObject();
    }
 
    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

방법 2. application.properties를 이용한 연결

 

application.properties에서 설정할 경우 sqlSessionFactory와 같은 역할

#DB접속 설정
spring.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/테이블 이름
spring.datasource.username= 아이디
spring.datasource.password= 비밀번호

#mapper위치 설정
mybatis.mapper-locations:classpath:/mappers/*.xml 
mybatis.type-aliases-package = com.ex.toypj.mapper

 

 

참조

https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

 

 

'Spring Boot' 카테고리의 다른 글

{Spring Boot} - Maven과 Gradle  (0) 2022.06.27
{Spring Boot} - api 연결하기  (0) 2022.06.22
{Spring Boot} - MyBatis사용법  (0) 2022.06.20
{Spring Boot} - 외부 세팅 application.properties  (0) 2022.06.20
{Mybatis} - Mybatis란  (0) 2022.06.20
Comments