mybatisplus+实验

feasure
xce 2026-01-08 00:21:03 +08:00
parent e19b3cd999
commit 4e52ada786
10 changed files with 390 additions and 134 deletions

View File

@ -106,8 +106,8 @@ token:
# 令牌有效期默认30分钟 # 令牌有效期默认30分钟
expireTime: 30 expireTime: 30
# MyBatis配置 # MyBatis Plus配置
mybatis: mybatis-plus:
# 搜索指定包别名 # 搜索指定包别名
typeAliasesPackage: com.agri.**.domain typeAliasesPackage: com.agri.**.domain
# 配置mapper的扫描找到所有的mapper.xml映射文件 # 配置mapper的扫描找到所有的mapper.xml映射文件

View File

@ -126,7 +126,12 @@
<groupId>javax.servlet</groupId> <groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId> <artifactId>javax.servlet-api</artifactId>
</dependency> </dependency>
<!-- ruoyi-springboot2 / mybatis-plus 配置 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -1,132 +0,0 @@
package com.agri.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 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.agri.common.utils.StringUtils;
/**
* Mybatis*
*
* @author ruoyi
*/
@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 SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
return sessionFactory.getObject();
}
}

View File

@ -0,0 +1,62 @@
package com.agri.framework.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* Mybatis Plus
*
* @author ruoyi
*/
@EnableTransactionManagement(proxyTargetClass = true)
@Configuration
public class MybatisPlusConfig
{
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor()
{
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
interceptor.addInnerInterceptor(paginationInnerInterceptor());
// 乐观锁插件
interceptor.addInnerInterceptor(optimisticLockerInnerInterceptor());
// 阻断插件
interceptor.addInnerInterceptor(blockAttackInnerInterceptor());
return interceptor;
}
/**
* https://baomidou.com/guide/interceptor-pagination.html
*/
public PaginationInnerInterceptor paginationInnerInterceptor()
{
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
// 设置数据库类型为mysql
paginationInnerInterceptor.setDbType(DbType.MYSQL);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
paginationInnerInterceptor.setMaxLimit(-1L);
return paginationInnerInterceptor;
}
/**
* https://baomidou.com/guide/interceptor-optimistic-locker.html
*/
public OptimisticLockerInnerInterceptor optimisticLockerInnerInterceptor()
{
return new OptimisticLockerInnerInterceptor();
}
/**
* https://baomidou.com/guide/interceptor-block-attack.html
*/
public BlockAttackInnerInterceptor blockAttackInnerInterceptor()
{
return new BlockAttackInnerInterceptor();
}
}

View File

@ -0,0 +1,104 @@
package com.agri.system.controller;
import com.agri.common.annotation.Log;
import com.agri.common.core.controller.BaseController;
import com.agri.common.core.domain.AjaxResult;
import com.agri.common.core.page.TableDataInfo;
import com.agri.common.enums.BusinessType;
import com.agri.common.utils.poi.ExcelUtil;
import com.agri.system.domain.SysStudent;
import com.agri.system.service.ISysStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
/**
* Controller
*
* @author ruoyi
*/
@RestController
@RequestMapping("/system/student")
public class SysStudentController extends BaseController
{
@Autowired
private ISysStudentService sysStudentService;
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:list')")
@GetMapping("/list")
public TableDataInfo list(SysStudent sysStudent)
{
startPage();
List<SysStudent> list = sysStudentService.queryList(sysStudent);
return getDataTable(list);
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:export')")
@Log(title = "学生信息", businessType = BusinessType.EXPORT)
@GetMapping("/export")
public AjaxResult export(SysStudent sysStudent)
{
List<SysStudent> list = sysStudentService.queryList(sysStudent);
ExcelUtil<SysStudent> util = new ExcelUtil<SysStudent>(SysStudent.class);
return util.exportExcel(list, "student");
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:query')")
@GetMapping(value = "/{studentId}")
public AjaxResult getInfo(@PathVariable("studentId") Long studentId)
{
return AjaxResult.success(sysStudentService.getById(studentId));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:add')")
@Log(title = "学生信息", businessType = BusinessType.INSERT)
@PostMapping
public AjaxResult add(@RequestBody SysStudent sysStudent)
{
return toAjax(sysStudentService.save(sysStudent));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:edit')")
@Log(title = "学生信息", businessType = BusinessType.UPDATE)
@PutMapping
public AjaxResult edit(@RequestBody SysStudent sysStudent)
{
return toAjax(sysStudentService.updateById(sysStudent));
}
/**
*
*/
@PreAuthorize("@ss.hasPermi('system:student:remove')")
@Log(title = "学生信息", businessType = BusinessType.DELETE)
@DeleteMapping("/{studentIds}")
public AjaxResult remove(@PathVariable Long[] studentIds)
{
return toAjax(sysStudentService.removeByIds(Arrays.asList(studentIds)));
}
}

View File

@ -0,0 +1,131 @@
package com.agri.system.domain;
import com.agri.common.annotation.Excel;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.Date;
/**
* sys_student
*
* @author ruoyi
*/
@TableName(value = "sys_student")
public class SysStudent implements Serializable
{
@TableField(exist = false)
private static final long serialVersionUID = 1L;
/** 编号 */
@TableId(type = IdType.AUTO)
private Long studentId;
/** 学生名称 */
@Excel(name = "学生名称")
private String studentName;
/** 年龄 */
@Excel(name = "年龄")
private Integer studentAge;
/** 爱好0代码 1音乐 2电影 */
@Excel(name = "爱好", readConverterExp = "0=代码,1=音乐,2=电影")
private String studentHobby;
/** 性别0男 1女 2未知 */
@Excel(name = "性别", readConverterExp = "0=男,1=女,2=未知")
private String studentSex;
/** 状态0正常 1停用 */
@Excel(name = "状态", readConverterExp = "0=正常,1=停用")
private String studentStatus;
/** 生日 */
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "生日", width = 30, dateFormat = "yyyy-MM-dd")
private Date studentBirthday;
public void setStudentId(Long studentId)
{
this.studentId = studentId;
}
public Long getStudentId()
{
return studentId;
}
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public String getStudentName()
{
return studentName;
}
public void setStudentAge(Integer studentAge)
{
this.studentAge = studentAge;
}
public Integer getStudentAge()
{
return studentAge;
}
public void setStudentHobby(String studentHobby)
{
this.studentHobby = studentHobby;
}
public String getStudentHobby()
{
return studentHobby;
}
public void setStudentSex(String studentSex)
{
this.studentSex = studentSex;
}
public String getStudentSex()
{
return studentSex;
}
public void setStudentStatus(String studentStatus)
{
this.studentStatus = studentStatus;
}
public String getStudentStatus()
{
return studentStatus;
}
public void setStudentBirthday(Date studentBirthday)
{
this.studentBirthday = studentBirthday;
}
public Date getStudentBirthday()
{
return studentBirthday;
}
@Override
public String toString() {
return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)
.append("studentId", getStudentId())
.append("studentName", getStudentName())
.append("studentAge", getStudentAge())
.append("studentHobby", getStudentHobby())
.append("studentSex", getStudentSex())
.append("studentStatus", getStudentStatus())
.append("studentBirthday", getStudentBirthday())
.toString();
}
}

View File

@ -0,0 +1,14 @@
package com.agri.system.mapper;
import com.agri.system.domain.SysStudent;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* Mapper
*
* @author ruoyi
*/
public interface SysStudentMapper extends BaseMapper<SysStudent>
{
}

View File

@ -0,0 +1,22 @@
package com.agri.system.service;
import com.agri.system.domain.SysStudent;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* Service
*
* @author ruoyi
*/
public interface ISysStudentService extends IService<SysStudent>
{
/**
*
*
* @param sysStudent
* @return
*/
public List<SysStudent> queryList(SysStudent sysStudent);
}

View File

@ -0,0 +1,43 @@
package com.agri.system.service.impl;
import com.agri.common.utils.StringUtils;
import com.agri.system.domain.SysStudent;
import com.agri.system.mapper.SysStudentMapper;
import com.agri.system.service.ISysStudentService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Service
*
* @author ruoyi
*/
@Service
public class SysStudentServiceImpl extends ServiceImpl<SysStudentMapper, SysStudent> implements ISysStudentService
{
@Override
public List<SysStudent> queryList(SysStudent sysStudent)
{
// 注意mybatis-plus lambda 模式不支持 eclipse 的编译器
// LambdaQueryWrapper<SysStudent> queryWrapper = Wrappers.lambdaQuery();
// queryWrapper.eq(SysStudent::getStudentName, sysStudent.getStudentName());
QueryWrapper<SysStudent> queryWrapper = Wrappers.query();
if (StringUtils.isNotEmpty(sysStudent.getStudentName()))
{
queryWrapper.eq("student_name", sysStudent.getStudentName());
}
if (StringUtils.isNotNull(sysStudent.getStudentAge()))
{
queryWrapper.eq("student_age", sysStudent.getStudentAge());
}
if (StringUtils.isNotEmpty(sysStudent.getStudentHobby()))
{
queryWrapper.eq("student_hobby", sysStudent.getStudentHobby());
}
return this.list(queryWrapper);
}
}

View File

@ -36,6 +36,7 @@
<spring-security.version>5.7.14</spring-security.version> <spring-security.version>5.7.14</spring-security.version>
<spring-framework.version>5.3.39</spring-framework.version> <spring-framework.version>5.3.39</spring-framework.version>
<knife4j.version>3.0.3</knife4j.version> <knife4j.version>3.0.3</knife4j.version>
<mybatis-plus.version>3.5.1</mybatis-plus.version>
</properties> </properties>
<!-- 依赖声明 --> <!-- 依赖声明 -->
@ -225,6 +226,12 @@
<artifactId>agri-api</artifactId> <artifactId>agri-api</artifactId>
<version>${agri.version}</version> <version>${agri.version}</version>
</dependency> </dependency>
<!-- ruoyi-springboot2 / mybatis-plus 配置 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
</dependencies> </dependencies>
</dependencyManagement> </dependencyManagement>