spring-boot集成mybatis
2017-10-12 本文已影响59人
aef5bc56a01e
前言
闲来没事,总结下spring-boot集成mybatis,以及mybatis分页(PageHelper)应用,项目地址
Step 1: 创建工程
如果用的IDEA作为开发工具,在New>Project,选择Spring Initializr,然后在SQL模块中勾选mybatis(根据自己的需求选择需要的模块), 如下图:
create-springboot-mybatis.png如果用的其他IDE,则可在pom中添加如下依赖:
<dependencies>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--我用的容器是undertow,所以添加了此依赖,并且去除了tomcat依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
</dependencies>
Step 2: 添加pagehelper依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.1.0</version>
</dependency>
Step 3: 配置DataSource,及mybatis
- application.yml
mybatis:
mapper-locations: classpath:mapper/*.xml
config-location: classpath:META-INF/mybatis-config.xml
spring:
datasource:
url: jdbc:mysql://10.1.9.47:3306/zeus?useUnicode=true&characterEncoding=utf8&autoReconnect=true
username: qiji
password: qiji,123
server:
port: 8080
context-path: /
- mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="false"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="mapUnderscoreToCamelCase" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
</settings>
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<property name="reasonable" value="true"/>
<property name="supportMethodsArguments" value="true"/>
<property name="returnPageInfo" value="check"/>
<property name="return" value="count=countSql"/>
</plugin>
</plugins>
</configuration>
- 在启动类上面添加@MapperScan标注,
Step 3: 编写相应的Mapper,Service,及controller
此部分代码可参看项目代码,此处贴一下PageHelper的应用代码
- UserMapper.java
package com.lyf.demo.mapper;
import com.lyf.demo.entity.User;
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.Page;
import java.util.Map;
public interface UserMapper{
Page<User> paging(Map<String, Object> params);
}
- UserService.java
package com.lyf.demo.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.Page;
import com.lyf.demo.entity.User;
import com.lyf.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserService {
@Autowired
private UserMapper userMapper;
public PageInfo<User> paging(int page){
PageHelper.startPage(page, 20);
Page<User> dbResult = userMapper.paging(null);
PageInfo<User> result = new PageInfo<>(dbResult);
return result;
}
}
如果你的项目是单模块应用,则以上配置,就可以了,如果是多模块,多个模块共享一个mapper模块,则需要自己编写相应的Config类
package com.oqiji.adanos.conf;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@AutoConfigureAfter(MyBatisConfig.class)
public class MyBatisMapperScannerConfig {
private static final Logger logger = LoggerFactory.getLogger(MyBatisMapperScannerConfig.class);
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
mapperScannerConfigurer.setBasePackage("com.lyf.demo.mapper");
logger.debug("config mybatis mapper scan");
return mapperScannerConfigurer;
}
}
package com.oqiji.adanos.conf;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import javax.sql.DataSource;
@Configuration
@EnableTransactionManagement
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MyBatisConfig implements TransactionManagementConfigurer {
private static final Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactory sqlSessionFactoryBean() {
logger.debug("start create sqlSessionFactory and config mybatis");
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
bean.setTypeAliasesPackage("com.lyf.demo.entity");
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
bean.setConfigLocation(resolver.getResource("classpath:META-INF/mybatis-config.xml"));
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);
}
}