Spring Boot 통합 MyBatis 방법
MyBatis 를 통합 하기 전에,우 리 는 먼저 druid 데이터 원본 을 설정 합 니 다.
스프링 부츠 통합 druid
druid
여러 설정 옵션 이 있 습 니 다.Spring Boot 의 설정 파일 을 사용 하면 편리 하 게 설정 할 수 있 습 니 다druid
.application.yml
프로필 에 쓰기:
spring:
datasource:
name: test
url: jdbc:mysql://192.168.16.137:3306/test
username: root
password:
# druid
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
여 기 는type: com.alibaba.druid.pool.DruidDataSource
설정 을 통 해 설정 하면 됩 니 다!봄 부츠 통합 MyBatis
Spring Boot 통합 MyBatis 는 두 가지 방식 이 있 습 니 다.간단 한 방법 은 MyBatis 가 공식 적 으로 제공 하 는 것 입 니 다.
mybatis-spring-boot-starter
또 다른 방식 은 여전히 유사 한
mybatis-spring
설정 방식 을 사용 하 는 것 이다.이런 방식 은 스스로 코드 를 써 야 하지만 MyBatis 의 각종 설정 을 편리 하 게 제어 할 수 있다.1.my batis-spering-boot-starter 방식
pom.xml
에 의존 도 를 추가 합 니 다:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.0.0</version>
</dependency>
mybatis-spring-boot-starter
의존 나 무 는 다음 과 같다.
mybatis:
mapperLocations: classpath:mapper/*.xml
typeAliasesPackage: tk.mapper.model
위 에서 흔히 볼 수 있 는 두 가지 설정 외 에 도:2.my batis-spering 방식
이런 방식 은 일반적인 용법 과 비교적 가깝다.mybatis 의존 과 mybatis-spring 의존 을 추가 해 야 합 니 다.
그리고 MyBatisConfig 설정 클래스 를 만 듭 니 다:
/**
* MyBatis
*/
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
@Autowired
DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("tk.mybatis.springboot.model");
//
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("reasonable", "true");
properties.setProperty("supportMethodsArguments", "true");
properties.setProperty("returnPageInfo", "check");
properties.setProperty("params", "count=countSql");
pageHelper.setProperties(properties);
//
bean.setPlugins(new Interceptor[]{pageHelper});
// XML
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
return bean.getObject();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
}
위의 코드 는 하나SqlSessionFactory
와 하나SqlSessionTemplate
를 만 들 었 습 니 다.주석 업 무 를 지원 하기 위해@EnableTransactionManagement
주 해 를 추가 하고 하나PlatformTransactionManagerBean
를 되 돌 렸 습 니 다.또한 이 설정 에
MapperScannerConfigurer
이 없 음 을 알 아야 합 니 다.MyBatis 의 Mapper 인 터 페 이 스 를 스 캔 하려 면 이 종 류 를 설정 해 야 합 니 다.이 설정 은 하나의 클래스 에 따로 넣 어야 합 니 다.
/**
* MyBatis
*/
@Configuration
//TODO , MapperScannerConfigurer ,
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("tk.mybatis.springboot.mapper");
return mapperScannerConfigurer;
}
}
이 설정 은 반드시 주의해 야 합 니 다@AutoConfigureAfter(MyBatisConfig.class)
.이 설정 이 있어 야 합 니 다.그렇지 않 으 면 이상 이 있 을 수 있 습 니 다.원인 은 바로 이런 종류의 집행 이 비교적 이 르 기 때문이다.sqlSessionFactory
아직 존재 하지 않 기 때문에 후속 집행 이 잘못 되 었 다.위 설정 을 완료 하면 MyBatis 를 사용 할 수 있 습 니 다.
페이지 플러그 인과 유 니 버 설 Mapper 통합 에 대하 여
페이지 플러그 인 은 플러그 인의 예 로 위의 코드 에 있 습 니 다.
유 니 버 설 Mapper 설정 은 실제 설정
MapperScannerConfigurer
일 때 사용tk.mybatis.spring.mapper.MapperScannerConfigurer
하면 되 며,속성 설정Properties
을 사용 하면 됩 니 다.Spring Boot 통합 MyBatis 의 기본 프로젝트
저 는 github 에 두 번 째 방식 의 통합 프로젝트 를 올 렸 고 페이지 플러그 인과 유 니 버 설 Mapper 를 통합 시 켰 습 니 다.프로젝트 는 간단 한 설정 과 조작 을 포함 하여 참고 로 만 들 었 습 니 다.
프로젝트 주소:https://github.com/abel533/MyBatis-Spring-Boot
페이지 플러그 인과 유 니 버 설 Mapper 에 관 한 정 보 는 위 주 소 를 통 해 찾 을 수 있 습 니 다.
총결산
이상 은 이 글 의 모든 내용 입 니 다.본 고의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가 치 를 가지 기 를 바 랍 니 다.여러분 의 저희 에 대한 지지 에 감 사 드 립 니 다.더 많은 내용 을 알 고 싶다 면 아래 링크 를 보 세 요.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.