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導入 路徑如下: ,若用/static/jquery-3.3.1.js會找不到,此時jQuery存放目錄仍爲/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>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章