-
[3/3] 스프링부트 데이터베이스 연결하기 (hikari,mysql,mybatis)카테고리 없음 2022. 5. 29. 16:51반응형
1. application.properties에 데이터 소스 설정
spring.datasource.hikari.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.hikari.jdbc-url: jdbc:mysql://localhost:3306/board?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC spring.datasource.hikari.username=root spring.datasource.hikari.password=root mybatis.configuration.map-underscore-to-camel-case=true
2. DatabaseConfiguration file 생성
package board.configuration; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import board.service.BoardService; @Configuration @PropertySource("classpath:/application.properties") public class DatabaseConfiguration { @Autowired private ApplicationContext applicationContext; @Bean @ConfigurationProperties(prefix="spring.datasource.hikari") public HikariConfig hikariConfig() { return new HikariConfig(); } @Bean public DataSource dataSource() throws Exception{ DataSource dataSource = new HikariDataSource(hikariConfig()); System.out.println("여기다"+dataSource.toString()); return dataSource; } @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations( applicationContext.getResources("classpath:/mapper/**/sql-*.xml") ); sqlSessionFactoryBean.setConfiguration(mybatisConfig()); return sqlSessionFactoryBean.getObject(); } @Bean public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory){ return new SqlSessionTemplate(sqlSessionFactory); } @Bean @ConfigurationProperties(prefix = "mybatis.configuration") public org.apache.ibatis.session.Configuration mybatisConfig() { return new org.apache.ibatis.session.Configuration(); } }
반응형