pom.xml
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> </parent> <modelVersion>4.0.0</modelVersion> <dependencies> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3.4</version> <optional>true</optional> </dependency> </dependencies> </project>
application.yml
# MyBatis配置
mybatis:
# 搜尋指定包別名
typeAliasesPackage: com.XX.**.domain.**
# 配置mapper的掃描,找到所有的mapper.xml對映檔案
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 載入全域性的配置檔案
configLocation: classpath:mybatis/mybatis-config.xml
mybatisplus配置類
package com.example.config; import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * User: Administrator * Date: 2020/4/7 * Time: 16:00 * Desc: */ @Configuration public class MybatisPlusConfig { /** * mybatis-plus SQL執行效率外掛【生產環境可以關閉】 */ @Bean public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } /** * 分頁外掛 */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } }
model
import com.baomidou.mybatisplus.annotation.TableName; import com.wgh.common.core.domain.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import java.util.Date; @EqualsAndHashCode(callSuper = true) @Data @TableName("task_management") public class TaskManagement extends BaseEntity { private Long id; private String taskName; private String taskGroupName = "default"; /** * 執行週期 不為空則按照週期執行 */ private String cron; private Integer taskFlag = 0; // 啟用 1 /停用 0 private Integer taskStatus; // 成功 1 | 未執行 0 | 失敗 2 private String taskFlowJson; }
dao
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.wgh.web.domain.taskManagement.TaskManagement; public interface TaskManagementMapper extends BaseMapper<TaskManagement> { }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.wgh.web.mapper.taskManagement.TaskManagementMapper"> </mapper>
service
import com.wgh.web.domain.taskManagement.TaskManagement; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; public interface ITaskManagementService extends IService<TaskManagement> { /** * 列表查詢 * * @param object 查詢引數 * @return 返回列表 */ List<TaskManagement> getList(TaskManagement object); /** * 修改停用啟用狀態 * * @param id 任務ID * @return 0|修改失敗 1|修改成功 */ int modifyTaskFlag(Long id); }
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.wgh.common.utils.SecurityUtils; import com.wgh.web.domain.taskManagement.TaskManagement; import com.wgh.web.mapper.taskManagement.TaskManagementMapper; import com.wgh.web.service.taskManagement.ITaskManagementService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class TaskManagementServiceImpl extends ServiceImpl<TaskManagementMapper, TaskManagement> implements ITaskManagementService { private static final Logger log = LoggerFactory.getLogger(TaskManagementServiceImpl.class); @Resource private TaskManagementMapper taskManagementMapper; /** * 列表查詢 * * @param object 查詢引數 * @return 返回列表 */ @Override public List<TaskManagement> getList(TaskManagement object) { QueryWrapper<TaskManagement> queryWrapper = new QueryWrapper<>(); return taskManagementMapper.selectList(queryWrapper); } /** * 修改停用啟用狀態 * * @param id 任務ID * @return 0|修改失敗 1|修改成功 */ @Override @Transactional public int modifyTaskFlag(Long id) { TaskManagement tmp = this.baseMapper.selectById(id); return this.baseMapper.updateById(tmp); } }
MyBatisConfig
package com.wgh.framework.config; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import javax.sql.DataSource; import org.apache.ibatis.io.VFS; import org.apache.ibatis.session.SqlSessionFactory; import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.boot.autoconfigure.SpringBootVFS; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.ClassUtils; import com.wgh.common.utils.StringUtils; /** * Mybatis支援*匹配掃描包 * * @author maj */ @Configuration public class MyBatisConfig { @Autowired private Environment env; static final String DEFAULT_RESOURCE_PATTERN = "**/*.class"; public static String setTypeAliasesPackage(String typeAliasesPackage) { ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); List<String> allResult = new ArrayList<String>(); try { for (String aliasesPackage : typeAliasesPackage.split(",")) { List<String> result = new ArrayList<String>(); aliasesPackage = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(aliasesPackage.trim()) + "/" + DEFAULT_RESOURCE_PATTERN; Resource[] resources = resolver.getResources(aliasesPackage); if (resources != null && resources.length > 0) { MetadataReader metadataReader = null; for (Resource resource : resources) { if (resource.isReadable()) { metadataReader = metadataReaderFactory.getMetadataReader(resource); try { result.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage().getName()); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } } if (result.size() > 0) { HashSet<String> hashResult = new HashSet<String>(result); allResult.addAll(hashResult); } } if (allResult.size() > 0) { typeAliasesPackage = String.join(",", (String[]) allResult.toArray(new String[0])); } else { throw new RuntimeException("mybatis typeAliasesPackage 路徑掃描錯誤,引數typeAliasesPackage:" + typeAliasesPackage + "未找到任何包"); } } catch (IOException e) { e.printStackTrace(); } return typeAliasesPackage; } public Resource[] resolveMapperLocations(String[] mapperLocations) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); List<Resource> resources = new ArrayList<Resource>(); if (mapperLocations != null) { for (String mapperLocation : mapperLocations) { try { Resource[] mappers = resourceResolver.getResources(mapperLocation); resources.addAll(Arrays.asList(mappers)); } catch (IOException e) { // ignore } } } return resources.toArray(new Resource[resources.size()]); } @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage"); String mapperLocations = env.getProperty("mybatis.mapperLocations"); String configLocation = env.getProperty("mybatis.configLocation"); typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage); VFS.addImplClass(SpringBootVFS.class); final MybatisSqlSessionFactoryBean sessionFactory = new MybatisSqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource); sessionFactory.setTypeAliasesPackage(typeAliasesPackage); sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ","))); sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation)); return sessionFactory.getObject(); } }
注意事項:必須使用 com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean 去替換 mybatis 的 SqlSessionFactoryBean (org.mybatis.spring.SqlSessionFactoryBean) 方才能完成對XML等預設SQL的新增處理