개인기록
[오류/해결] spring boot mybatis insert가 안되는 오류
ran4
2022. 11. 5. 22:51
환경
java 8, mybatis, spring boot, maven project
개요
테스트는 통과하는데 정작 DB에 데이터가 추가가 안되는 오류가 있었다
콘솔로 insert를 하면 auto increment로 설정한 Id값이 올라갔기 때문에
어떤 설정이 잘못된건지 찾기가 어려웠다
해결
테스트 어노테이션을 바꾸니 제대로 데이터가 추가되었다
변경 전
@MybatisTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class AdminMapperTest {
@Autowired
private AdminMapper mapper;
@Test
@DisplayName("insert 테스트")
void productEnrollTest() throws Exception {
/* 이하 내용 생략 */
}
}
변경 후
//@MybatisTest
//@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@WebAppConfiguration
@SpringBootTest
class AdminMapperTest {
@Autowired
private AdminMapper mapper;
@Test
@DisplayName("insert 테스트")
void productEnrollTest() throws Exception {
/* 이하 내용 생략 */
}
}
DB에 제대로 추가되었다
++DBConfig 설정
@Configuration
@PropertySource("classpath:/application.properties")
@MapperScan(basePackages = "mapper혹은 dao 패키지 경로")
public class DatabaseConfig {
@Autowired
private ApplicationContext applicationContext;
public DatabaseConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Bean
public HikariConfig hikariConfig() {
return new HikariConfig();
}
@Primary
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() throws Exception {
return DataSourceBuilder.create().type(HikariDataSource.class).build();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("dto 패키지 경로");
bean.setMapperLocations(applicationContext.getResources("classpath:mapper/*.xml"));
return bean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
}