수업/정리

220511 Springboot3 - mybatis연동, DataAccess(DB연동)

jumphare 2022. 5. 11. 21:07

*스프링부트

*mybatis 연동
프로젝트 생성 시 Dependencies 체크할 부분
web - Spring Web
SQL - MyBatis Framework, oracle Driver
Developer Tools - Lombok

*환경파일 설정
main / resources / application.properties

# oracle
spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe
spring.datasource.username=spring
spring.datasource.password=spring123

# mybatis    (classpath:resources디렉토리)
mybatis.config-location=classpath:mybatis-config.xml  //이 파일은 그런데 안의 내용이 적용이 안 되기 때문에.. 파일 지워도 문제 없음
mybatis.mapper-locations=classpath:mapper/*.xml  //얘는 당연히 필요함 삭제 ㄴㄴ

*DataAccess 파일 생성
/main/java/com/example/demo/config/DataAccessConfig.java
---> spring에서 root-context.xml에 추가했던 db연동에 대한 bean 생성을 여기서 함

 

@PropertySource("classpath:/application.properties") ; 괄호의 파일을 불러옴
@ConfigurationProperties(prefix = "spring.datasource") : spring.datasource로 시작하는 변수의 prefix 지정
@Bean : 클래스의 Bean 객체를 생성

@Configuration
@PropertySource("classpath:/application.properties")          
public class DataAccessConfig {

   @ConfigurationProperties(prefix = "spring.datasource")    
   public DataSource dataSource() {
      return DataSourceBuilder.create().build();
   }


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

      factoryBean.setDataSource(dataSource);
      factoryBean.setMapperLocations(
         new PathMatchingResourcePatternResolver().getResources("classpath:/mapper/*.xml")

      );
      factoryBean.setTypeAliasesPackage("com.example.demo.model"); // DTO Alias 설정
      return factoryBean.getObject();
   }

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

----> factoryBean.setTypeAliasesPackage("com.example.demo.model");     // DTO Alias 설정, 공통 디렉토리 생략시켜줌
@Getter
@Setter
@Alias("board")    <-- 이런 식으로 Alias를 DTO 클래스에 바로 붙여 별칭을 사용할 수 있음
public class Board {
---> 즉 board인 class를 찾으면 com.example.demo.model 경로에서 Alias가 일치하는 이 클래스를 가져가는것