SpringBoot整合mybatis,

一.新建项目
在这里插入图片描述

1.组名 2.项目名 1+2为9默认的包名
3.选择项目构建jar管理mvn、graddle等
4.项目构建语言java、kotlin、grovey等
5.项目打包设置,jar或war
6.java版本

在这里插入图片描述
选择web、thymeleaf、MySQL、Mybatis,新建项目结构如下
在这里插入图片描述
这里用已经搭建的项目来直接介绍
在这里插入图片描述
application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/test?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&allowMultiQueries=true
    username: 
    password: 
    type: org.apache.commons.dbcp.BasicDataSource
  servlet:
    multipart:
      enabled: true
      max-file-size: 100MB
      max-request-size: 100MB
mybatis:
  mapperLocations: classpath:mapper/*.xml
  type-aliases-package: com.base.pojo

jQuery导入 路径如下:
<script src="/jquery-3.3.1.js"></script>,若用/static/jquery-3.3.1.js会找不到,此时jQuery在idea存放目录为/static/jquery-3.3.1.js

Controller


@Controller
public class MyController {
    @Autowired
    IBatchService iBatchService;

    @RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
    @ResponseBody
    public Result fileUpload(MultipartFile file, HttpServletRequest request) throws EtlException {
        if (file.isEmpty()) {
            throw new EtlException("未选择文件!");
        }
        String filePath = request.getSession().getServletContext().getRealPath("/")
                + file.getOriginalFilename();
        String description = request.getParameter("description");
        if (StringUtils.isEmpty(description)) {
            throw new EtlException("输入为空!");
        }
        long batchId = iBatchService.insertFile(description, 0);
        try {
            file.transferTo(new File(filePath));
        } catch (Exception e) {
            throw new EtlException("文件上传失败!");
        }
        return Result.success();
    }

    @RequestMapping("test")
    public String test() {
        return "/rmdb";
    }

    @RequestMapping("db")
    @ResponseBody
    public Result db(HttpServletRequest request) throws EtlException {
        String column = request.getParameter("column");
        String description = request.getParameter("description");
        String tableName = request.getParameter("tableName");
        if (StringUtils.isEmpty(column) || StringUtils.isEmpty(description) || StringUtils.isEmpty(tableName)) {
            throw new EtlException("输入为空");
        }
        
        return Result.success();
    }
}

Dao

@Repository
public interface IBatchDao {
    int insertFile(BatchInfo batchInfo);
}

Exception

public class EtlException extends Exception{
    private String message;

    public EtlException(String message) {
        super(message);
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


import com.google.gson.Gson;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Configuration    //这里springboot自动扫描配置自定义全集异常处理器
public class EtlExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) {
        e.printStackTrace();
        String message = "请稍后重试!";
        if(e instanceof EtlException || StringUtils.isEmpty(e.getMessage())){
            message = ((EtlException)e).getMessage();
            HandlerMethod handlerMethod = (HandlerMethod)handler;
            ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
            if(responseBody!=null){
                Map<String,Object> responseMap = new HashMap<>();
                responseMap.put("code","999999");
                responseMap.put("message",message);
                String json = new Gson().toJson(responseMap);
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json;charset=utf-8");
                try {
                    httpServletResponse.getWriter().write(json);
                    httpServletResponse.getWriter().flush();
                }catch (IOException e1){
                    e1.printStackTrace();
                }
            }
        }
        return new ModelAndView();
    }
}

POJO

public class BatchInfo {
    private long batchId;
    private String description;
    private int fileType;

    public long getBatchId() {
        return batchId;
    }

    public void setBatchId(long batchId) {
        this.batchId = batchId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getFileType() {
        return fileType;
    }

    public void setFileType(int fileType) {
        this.fileType = fileType;
    }
}


//Result  自定义 异步请求返回消息格式 
import java.util.Map;

public class Result {
    private String code;
    private String message;
    private Map<String, Object> data;

    public static Result success() {
        Result result = new Result();
        result.setCode("000000");
        result.setMessage("操作成功!");
        return result;
    }

    public static Result error() {
        Result result = new Result();
        result.setCode("999999");
        result.setMessage("操作失败!");
        return result;
    }

    public Result add(String key, Object value) {
        this.getData().put(key, value);
        return this;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }
}

Service


public interface IBatchService {
    long insertFile(String description ,int fileType);
}



import com.base.dao.IBatchDao;
import com.base.pojo.BatchInfo;
import com.base.service.IBatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BatchServiceImpl implements IBatchService {
    @Autowired
    IBatchDao iBatchDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
    public long insertFile(String description, int fileType) {
        BatchInfo batchInfo = new BatchInfo();
        batchInfo.setDescription(description);
        batchInfo.setFileType(fileType);
        iBatchDao.insertFile(batchInfo);
        return batchInfo.getBatchId();
    }
}

TransportApplication

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("base.dao")//这里为dao的包,不指定mybatis无法使用
public class TransportApplication {
    public static void main(String[] args) {
        SpringApplication.run(TransportApplication.class, args);
    }
}


IBatchMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
        "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

<mapper namespace="对应dao接口">
    <resultMap id="唯一id" type="对应pojo">
        <result column="batch_id" property="batchId"/>
        <result column="description" property="description"/>
        <result column="file_type" property="fileType"/>
    </resultMap>

    <insert id="insertFile" useGeneratedKeys="true" keyProperty="batchId">
        insert into batch(description,file_type) value (#{description},#{fileType})
    </insert>
</mapper>

文件上传

表单+文件
<form id="file_form">
    <input type="file" name="file"/>
    <input type="text" id="description" name="description" aria-placeholder="请数输入文件描述"/>
    <button type="button" onclick="submitFunction()">提交</button>
</form>

<script>
    function submitFunction() {
        //这里唯一需要注意的就是这个form-add的id
        var formData = new FormData($("#file_form")[0]);
        $.ajax({
            //接口地址
            url: '/fileUpload',
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                //成功的回调
                if (data.code == "000000") {
                    alert(data.message);
                } else {
                    alert(data.message);
                }
            },
            error: function (returndata) {
                //请求异常的回调
                // modals.warn("网络访问失败,请稍后重试!");
            }
        });
    }
</script>
----------------------------------------------------------
表单
<form id="form">
    <input type="text" id="tableName" name="tableName" placeholder="请输入表名" data-type="必填"/>
    <input type="text" id="column" name="column" placeholder="请输入数据列名空格分开(eg:a b c)" data-type="必填"/>
    <input type="text" id="description" name="description" placeholder="请输入描述信息" data-type="必填"/>
    <input type="button" id="submit" value="提交"/>
</form>


 $("#submit").click(function () {
        $.ajax({
            url: "/db",
            type: "POST",
            dataType: "json",
            data: $("#form").serialize(),
            success: function (rtn) {
                if (rtn.code == "000000") {
                    alert(rtn.message);
                } else {
                    alert(rtn.message);
                }
            }, error: function (rtn) {
                console.log(rtn);
            }
        });

    });

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">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.transport</groupId>
    <artifactId>transport</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>transport</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <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.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.44-1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>
</project>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值