스프링 부트와 MyBatis 연동시 예외 Invalid bound statement (not found) 해결 방법

김민우·2023년 1월 29일
0

코멘토과제

목록 보기
2/2

스프링 부트에서 MyBatis 연동 후 URL 접속하여 MyBatis 쿼리를 실행하니깐 다음 오류가 발생했다.

Mapper 인터페이스와 XML 파일의 위치와 내용은 다음과 같다.

경로

Mapper 인터페이스
package commento.HW3.settingweb.dao;

import org.apache.ibatis.annotations.Mapper;

import java.util.HashMap;

@Mapper
public interface StatisticMapper {
    HashMap<String, Object> selectYearLogin(String year);
}
Mapper XML
<?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="commento.HW3.settingweb.dao.StatisticMapper">

    <select id="selectYearLogin" parameterType="string" resultType="hashMap">
        select count(*) as totCnt
        from statistc.requestinfo ri
        where left(ri.createDate, 2) = #{year};
    </select>

</mapper>

XML파일에는 오타가 없었다. 특히, namespace 부분은 IntelliJ 엔터프라이즈 버전을 사용하면 오타가 없는지 확인할 수 있다.

구글링 결과 application.properties 파일에서 Mapper의 위치가 잘못됬을 수 있다하여 이 또한 확인해봤다.

application.properties
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://127.0.0.1:3306/statistc
spring.datasource.username=root
spring.datasource.password=12345678

mybatis.mapper-locations=classpath:/mapper/*.xml

설정 파일인 application.properties에도 제대로 경로가 입력되있는데 도대체 어디서 이런 오류가 발생한 것인지 궁금하였다.

원인은 MyBatis 설정파일인 MyBatisConfig.java에 있었다.

package commento.HW3;

import lombok.RequiredArgsConstructor;
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.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "commento.HW3.settingweb.dao")   // mapper 인터페이스의 경로와 동일해야 한다.
@RequiredArgsConstructor
public class MyBatisConfig {

    private final ApplicationContext applicationContext;

    @Bean
    public SqlSessionFactory sqlSessionFactory (DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage("commento.HW3.settingweb.dto");
        /* sqlSessionFactoryBean.setMapperLocations(
                applicationContext.getResources("classpath:/mapper/*.xml"
                ));
		*/ 
        return sqlSessionFactoryBean.getObject();
    }

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

sqlSessionFactoryBean 에도 XML파일의 경로를 주입해줘야 했다. 자세한 이유는 모르겠지만 이를 적용하니 예외가 발생하지 않고 실행되었다.

0개의 댓글