首页 > 基础资料 博客日记
MyBatisPlusの效率与提升
2024-10-29 09:00:05基础资料围观66次
本篇文章分享MyBatisPlusの效率与提升,对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识
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的添加处理
文章来源:https://www.cnblogs.com/supperlhg/p/18511289
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签:
上一篇:聊聊jvm的内存结构, 以及各种结构的作用
下一篇:KafKa动态分组ID