SpringBoot+MybatisPlus

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35002313/article/details/84898875

简介:

本人因领导要求 最近简单的使用了一下mybatis-plus,当然还是增删改查(分页)基础操作, 特总结 方便大家学习 

源码可下载

https://download.csdn.net/download/qq_35002313/10837664

第三方框架:

h2数据库(内存方式) 

参考地址  https://baike.baidu.com/item/H2/6687672

owner读取外部配置文件

参考地址  https://github.com/lviggiano/owner

mybatis-plus 简化开发

参考地址  https://mp.baomidou.com/

     开始使用吧

1. 引入maven依赖  大家肯定都能看懂的

 

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.flywaydb</groupId>
            <artifactId>flyway-core</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.6</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>1.1.2-beta4</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <!--<scope>runtime</scope>-->
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.aeonbits.owner</groupId>
            <artifactId>owner</artifactId>
            <version>1.0.9</version>
        </dependency>

 2.  编写springboot压缩文件application.yml   

  

spring:
  datasource:
      url: jdbc:h2:mem:file
      username: root
      password: root
      driver-class-name: org.h2.Driver

  h2:
    console:
      enabled: true
      path: /h2-console

mybatis-plus:
  mapper-locations:
     classpath: mapper:/*.xml
  type-aliases-package: com.example.entity

3. 因为本人使用的是h2数据库,所以需要在resource资源目录下创建一个schema.sql文件 用于项目启动时初始化表结构

create table tb_file(
id int IDENTITY PRIMARY KEY,
name varchar (50)not null,
uploadData DATE  not null
);



创建自己的实体类

@Data
@TableName(value = "tb_file")
public class FileEntity  implements Serializable {
    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

    @TableField(value = "name", exist = true)
    private String name;

    @TableField(value = "uploadData", exist = true)
    private Object date;

}

4.配置mybaits-plus分页插件

@Configuration
@MapperScan(value = "com.example.mapper")
public class MybatisPlusConfig {
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }

    /**
     * 打印 sql
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
        //格式化sql语句
        Properties properties = new Properties();
        properties.setProperty("format", "true");
        performanceInterceptor.setProperties(properties);
        return performanceInterceptor;
    }

5.编写自己的Mapper接口继承自mybatis-plus的BaseMapper<Entity entity>

public interface FileMapper extends BaseMapper<FileEntity> {
    /**
     * 分页
     * @param page 工具类
     * @return
     */
    @Select(value = "select * from tb_file")
    public List<FileEntity> find(Pagination page);
}

6.  编写自己的Service接口继承自mybatis-plus的IService<Entity entity>

public interface FileService  extends IService<FileEntity> {


    /**
     * 分页
     * @param page
     * @return
     */
    Page<FileEntity> getQuestionStudent(Page<FileEntity> page);

}

 7. 编写自己的serviceImpl实现类继承自myabtis-plus的ServiceImpl<FileMapper,FileEntity>实现自己的service接口

public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    @Override
    public Page<FileEntity> getQuestionStudent(Page<FileEntity> page) {
        return page.setRecords(this.baseMapper.find(page));
    }
}

8. 新建path.properties配置文件,用于存放文件地址

file.path=E:/File/

9. 新建SourcePathConfig用于加载配置文件

@Sources({ "classpath:path.properties" })
public interface SourcePathConfig extends Reloadable {

    @Key("file.path")
    String path();
}

10. 我这里基本的操作就写了, 没有大家可以去官网参考下

public class FileController {
    private final static SourcePathConfig servletConfg = ConfigCache.getOrCreate(SourcePathConfig.class);


    @Autowired
    private FileService fileService;


    /**
     * 传入实体save操作
     */
    @RequestMapping(value = "/save")
    public void save() {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName("aa");
        fileEntity.setDate(new Date());
        fileService.insert(fileEntity);
    }

    /**
     * 如果有id的话 就会进行更新
     * 如果无, 那么进行save操作
     */
    @RequestMapping(value = "/insertorupdate")
    public void insertorupdate() {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName("bb");
        fileEntity.setDate(new Date());
        fileService.insertOrUpdate(fileEntity);
    }


    /**
     * 更新
     */
    @RequestMapping(value = "/update")
    public void update() {
        FileEntity fileEntity = new FileEntity();
        fileEntity.setId(1);
        fileEntity.setName("aaaa");
        fileService.updateById(fileEntity);
    }

    /**
     * 单条件     qryWrapper.ge("数据库字段",参数名)
     * 慎用,有bug
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/get")
    @ResponseBody
    public FileEntity get(String name) {
        EntityWrapper<FileEntity> qryWrapper = new EntityWrapper<>();
        qryWrapper.ge("name", name);
        FileEntity fileEntity = fileService.selectOne(qryWrapper);
        return fileEntity;
    }

    /**
     * 多个参数使用map
     *
     * @return
     */
    @RequestMapping(value = "/getMap")
    @ResponseBody
    public List<FileEntity> getMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "aa");
        map.put("id", 1);
        List<FileEntity> fileEntity = fileService.selectByMap(map);
        return fileEntity;
    }


    /**
     * 接收参数EntityWrapper<FileEntity>默认查询所有
     * @return
     */
    @RequestMapping(value = "/getAll")
    @ResponseBody
    public List getAll() {
        EntityWrapper<FileEntity> qryWrapper = new EntityWrapper<>();
        List<FileEntity>list=fileService.selectList(qryWrapper);
        return list;
    }


    @RequestMapping(value = "/selectPage")
    @ResponseBody
    public Map selectPage(int page,int size){
        Map<String,Object>map=new HashMap<>();
        Page<FileEntity>fileEntityPage=fileService.selectPage(new Page<>(page,size));
        map.put("data",fileEntityPage);
        return map;
    }

    /**
     * 文件上传
     * 1. 判断是否有request请求
     * 2. 以MultipartHttpServletRequest来收
     * 3. 获取文件名称
     * 4. 根据名称获取文件内容
     * 5. 配置虚拟路径
     * 6 进行上传
     */
    @RequestMapping(value = "/filePut")
    @ResponseBody
    public String file(HttpServletRequest request) throws Exception {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        String filename = printFile(multipartResolver, request);
        if ("".equals(filename) || filename == null) {
            return  "请核对";
        }
        FileEntity fileSource = new FileEntity();
        fileSource.setName(filename);
        fileSource.setDate(new Date());
        add(fileSource);
        return "ok";
    }


    private String printFile(CommonsMultipartResolver commonsMultipartResolver, HttpServletRequest request) throws Exception {
        StringBuffer path = new StringBuffer(servletConfg.path());
        File file = new File(path.toString());
        if (!file.exists()) {
            file.mkdir();
        }
        file.setWritable(true, true);
        MultipartFile multipartFile = null;
        if (commonsMultipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iterator = multiRequest.getFileNames();
            while (iterator.hasNext()) {
                multipartFile = multiRequest.getFile(iterator.next());
                path.append(multipartFile.getOriginalFilename());
                File localFile = new File(path.toString());
                multipartFile.transferTo(localFile);
            }
        }
        return multipartFile.getOriginalFilename();
    }


    /**
     * 添加文件上传信息
     * @param fileSource
     * @return
     * @throws Exception
     */
    private void add(FileEntity fileSource) throws Exception {
        fileService.insert(fileSource);
    }


    /**
     * 文件下载
     * @param name
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/download")
    public void download(String name, HttpServletResponse response) throws Exception {
        if ("".equals(name) || name == null) {
            return;
        }
        File file = new File(servletConfg.path(), name);
        if (file.exists()) {
            response.setContentType("application/multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(name.getBytes("gb2312"), "ISO8859-1"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            fis.close();
            bis.close();
            os.close();
        }
    }


    /**
     * 删除文件
     * @param fileSource
     * @param filename
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    public String delete(FileEntity fileSource,String filename) throws Exception {
        boolean res = fileService.updateById(fileSource);
        if (res) {
            File file = new File(servletConfg.path()+filename);
            boolean delresponse = file.delete();
            if (delresponse) {
                return "redirect:/file/";
            }
        }
        return "redirect:/error";
    }

}

猜你喜欢

转载自blog.csdn.net/qq_35002313/article/details/84898875