SpringBoot+MyBatis+MySQL搭建web项目知识总结

所解决的问题

1、如何用idea创建springboot项目

2、如何进行 服务器、数据库、mybatis、视图解析器的配置

3、如何使用mybatis generator 自动生成代码

4、如何使用multipart进行文件上传

5、如何运用springboot的事务

6、如何打包进行tomcat部署

运用idea创建springboot项目

1、打开IDEA,File -> New -> Project,选择Spring Initializr,然后next。

2、修改Ariifact,下面的Name、package会自动修改;Packaging有两种模式,一种是Jar,一种是War;因为springboot中自带了tomcat,因此可以将项目打成jar,直接运行;而我现有项目是部署到tomcat上,因此我需要打成war包;然后next。

3、设置项目依赖,然后next ,进入下一页 ,设置project name,点击finish完成。

4、进入项目

5、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.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo002</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo002</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-jdbc</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-web-services</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 添加mybatis-generator依赖包,mybatis-generator是一款在使用mybatis框架时,自动生成model,dao和mapper的工具 -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>
</project>

无配置文件的springmvc

通过两个例子:1、http请求访问并渲染页面 2、http请求返回json字符串

-配置数据源、视图渲染

-添加视图渲染pom依赖

-创建WelcomeController、welcome.jsp

新增之后的项目结构

application.yml 配置数据源 和 视图渲染

# 数据源、试图配置
spring:
  datasource:
    url: jdbc:sqlserver://localhost:3306;DatabaseName="OneStudent"
    username: root
    password: 123456
    driver-class-name: com.microsoft.sqlserver.jdbc.SQLServerDriver

  mvc:
    view:
      prefix: /WEB-INF/views/
      suffix: .jsp

pom.xml新增视图渲染依赖

 <!-- 使用 jsp 必要依赖 -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

创建WelcomeController

package com.example.demo002.web;


import com.example.demo002.entity.Welcome;
import com.example.demo002.response.Response;
import com.example.demo002.response.ResponseCode;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/welcome")
public class WelcomeController {

    /*
    * 访问 welcome.jsp 页面
    * @return
    * */
    @RequestMapping("welcomeIndex")
    public ModelAndView welcomeIndex(){
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        mv.addObject("name","xx");
        return mv;
    }

    /*
    * 返回 json 字符串
    * @return
    * */
    @RequestMapping("getWelcomeInfo")
    @ResponseBody
    public Response getWelcomeInfo(){

        /*
        * 测试数据
        * */
        List<Welcome> welcomes = new ArrayList<>();
        Welcome w1 = new Welcome();
        w1.setId(1);
        w1.setName("xx1");
        w1.setAge(11);
        w1.setGender("女");

        Welcome w2 = new Welcome();
        w2.setId(2);
        w1.setName("xx2");
        w1.setAge(22);
        w1.setGender("男");

        welcomes.add(w1);
        welcomes.add(w2);

        Response response = new Response();
        response.setData(welcomes);
        response.setRetcode(ResponseCode.SUCCESS);
        response.setRetdesc("Success");
        return response;
    }
}

创建welcome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>视图渲染</title>
</head>
<body>
    您好,${name}
</body>
</html>

启动项目,并访问

使用mybatis generator自动生成代码

用于为表创建 *Mapper.xml、model、dao文件

在pom.xml 添加mybatis generator 自动生成代码插件

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

            <!-- mybatis generator 自动生成代码插件 -->
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                    <verbose>true</verbose>
                </configuration>
            </plugin>
        </plugins>
    </build>

在上面pom.xml配置的pugin路径resources/generator 文件夹下添加generatorConfig.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration
            PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
            "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包 -->
    <classPathEntry location="D:\package\mysql-connector-java-8.0.15\mysql-connector-java-8.0.15\mysql-connector-java-8.0.15.jar"/>
    <context id="DB2Tables"  targetRuntime="MyBatis3">

        <commentGenerator>
            <property name="suppressDate" value="false"/>
            <!-- 是否去除自动生成的注释 true:是 ;  false:否 -->
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!-- 数据库链接 URL,用户名、密码 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test"
                        userId="root"
                        password="123456">
        </jdbcConnection>

        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 生成模型的包名和位置,生成model实体类文件位置 -->
        <javaModelGenerator targetPackage="com.example.demo002.entity"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!-- 生成映射文件的包名和位置 -->
        <sqlMapGenerator targetPackage="mybatis"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!-- 生成DAO的包名和位置,生成mapper接口文件位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.example.demo002.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>

        <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名;
         需要生成的实体类对应的表名,多个实体类复制多份该配置即可-->
        <table tableName="onestudent"
               domainObjectName="StudentBinding"
               enableCountByExample="false"
               enableUpdateByExample="false"
               enableDeleteByExample="false"
               enableSelectByExample="false"
               selectByExampleQueryId="false">
        </table>
    </context>
</generatorConfiguration>

使用maven中的mybatis-generator:generate根据数据库里面表生产相关的类

Edit Configurations -> 添加 -> Maven

i

执行以上结果:生成了相应文件如下

 

配置mybatis

在application.yml 中添加mybatis的配置

# mybatis配置
mybatis:
  mapper-locations: classpath*:mybatis/*Mapper.xml
  type-aliases-package: com.example.demo002.entity

在StudentBindingMapper.java中添加 @Repository("studentBindingMapper")注解才能使用@MapperScan扫描到

package com.example.demo002.mapper;

import com.example.demo002.entity.StudentBinding;
import org.springframework.stereotype.Repository;

@Repository("studentBindingMapper")
public interface StudentBindingMapper {
    int insert(StudentBinding record);

    int insertSelective(StudentBinding record);
}

在SpringbootdemoApplication.java添加@MapperScan

package com.example.demo002;

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

@SpringBootApplication
@MapperScan("com.example.demo002.mapper")
public class Demo002Application {

    public static void main(String[] args) {
        SpringApplication.run(Demo002Application.class, args);
    }

}

添加service、controller层

项目层级

添加StudentBindingService

package com.example.demo002.service;

import com.example.demo002.entity.StudentBinding;

import java.util.List;

public interface StudentBindingService {
    int deleteByPrimaryKey(Long id);
    int insert(StudentBinding record);
    int insertSelective(StudentBinding record);
    StudentBinding selectByPrimaryKey(Long id);
    int updateByPrimaryKeySelective(StudentBinding record);
    int updateByPrimaryKey(StudentBinding record);
    void validTransaction(Long id);
    List<StudentBinding> getStudentBindByQuery(StudentBinding record);
}

添加StudentBindingServiceImpl

package com.example.demo002.service.impl;


import com.example.demo002.entity.StudentBinding;
import com.example.demo002.mapper.StudentBindingMapper;
import com.example.demo002.service.StudentBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;

@Service(value = "studentBindingService")
public class StudentBindingServiceImpl implements StudentBindingService {

    @Autowired
    private StudentBindingMapper studentBindingMapper;

    @Override
    public int deleteByPrimaryKey(Long id){
        return studentBindingMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(StudentBinding record){
        return studentBindingMapper.insert(record);
    }

    @Override
    public int insertSelective(StudentBinding record){
        return studentBindingMapper.insertSelective(record);
    }

    @Override
    public StudentBinding selectByPrimaryKey(Long id){
        return studentBindingMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(StudentBinding record){
        return studentBindingMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(StudentBinding record){
        return studentBindingMapper.updateByPrimaryKey(record);
    }

    @Override
    @Transactional
    public void validTransaction(Long id){
        // 删除之后,插入该id的数据
        studentBindingMapper.deleteByPrimaryKey(id);

        StudentBinding record = new StudentBinding();
        record.setId(id);
        studentBindingMapper.insertSelective(record);
    }

    @Override
    public List<StudentBinding> getStudentBindByQuery(
            StudentBinding record){
        return studentBindingMapper.getStudentBindByQuery(record);
    }
}

 

新增StudentBindingController

package com.example.demo002.web;


import com.example.demo002.entity.StudentBinding;
import com.example.demo002.response.Response;
import com.example.demo002.response.ResponseCode;
import com.example.demo002.service.StudentBindingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping(value = "/studentBind")
public class StudentBindingController {

    @Autowired
    private StudentBindingService studentBindingService;

    /*
    * 根据请求参数,删除绑定学生信息
    * @param id
    * @retutn
    * */
    @RequestMapping("deleteByPrimaryKey")
    @ResponseBody
    public Response deleteByPrimaryKey(Long id){
        Response response = new Response();
        if(id==null){
            response.setRetcode(ResponseCode.PARAMARTER_ERROR);
            response.setRetdesc("参数错误");
            return response;
        }
        try{
            studentBindingService.deleteByPrimaryKey(id);
            response.setRetcode(ResponseCode.SUCCESS);
            response.setRetdesc("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            response.setRetcode(ResponseCode.FAILED);
            response.setRetdesc("删除异常");
        }
        return response;
    }

    /*
    * 根据请求参数,添加绑定学生信息
    * @param record
    * @return
    * */
    @RequestMapping("insertSelective")
    @ResponseBody
    public Response insertSelective(StudentBinding record){
        Response response = new Response();
        if(record==null){
            response.setRetcode(ResponseCode.PARAMARTER_ERROR);
            response.setRetdesc("参数错误");
            return response;
        }

        try{
            studentBindingService.insertSelective(record);
            response.setRetcode(ResponseCode.SUCCESS);
            response.setRetdesc("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            response.setRetcode(ResponseCode.FAILED);
            response.setRetdesc("添加异常");
        }
        return response;
    }

    /*
    * 根据请求参数,查询绑定学生信息
    * @param id
    * @return
    * */
    @RequestMapping("selectByPrimaryKey")
    @ResponseBody
    public Response selectByPrimaryKey(Long id){

        Response response = new Response();
        if(id==null){
            response.setRetcode(ResponseCode.PARAMARTER_ERROR);
            response.setRetdesc("参数错误");
            return response;
        }

        try{
            StudentBinding studentBinding = studentBindingService.selectByPrimaryKey(id);
            response.setData(studentBinding);
            response.setRetcode(ResponseCode.SUCCESS);
            response.setRetdesc("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            response.setRetcode(ResponseCode.FAILED);
            response.setRetdesc("查询异常");
        }
        return response;
    }

    /*
    * 验证@Transaction注解是否好用
    * @param id
    * @return
    * */
    @RequestMapping("validTransaction")
    @ResponseBody
    public Response validTransaction(Long id){
        Response response = new Response();
        if(id==null){
            response.setRetcode(ResponseCode.PARAMARTER_ERROR);
            response.setRetdesc("参数错误");
            return response;
        }

        try{
            studentBindingService.validTransaction(id);
            response.setRetcode(ResponseCode.SUCCESS);
            response.setRetdesc("添加成功");
        }catch (Exception e){
            e.printStackTrace();
            response.setRetcode(ResponseCode.FAILED);
            response.setRetdesc("添加异常");
        }
        return response;

    }

    /*
    * 跳转到上传文件页面
    * @return
    * */
    @RequestMapping("multipartIndex")
    public String multipartIndex(){
        return "multipart-index";
    }

    /*
    * 上传文件到指定目录
    * @param file
    * @return
    * */
    @RequestMapping("/upload")
    @ResponseBody
    public Response upload(@RequestParam("file") MultipartFile file){
        Response response = new Response();
        if(file.isEmpty()){
            response.setRetcode(ResponseCode.PARAMARTER_ERROR);
            response.setRetdesc("参数错误");
            return response;
        }

        try{
            String filePath = "D:\\ceshi\\upload";
            File dir = new File(filePath);
            if(!dir.isDirectory()){
                dir.mkdir();
            }
            String fileOriginalName = file.getOriginalFilename();
            File writeFile = new File(filePath + fileOriginalName);
            // 文件写入磁盘
            file.transferTo(writeFile);

            response.setRetcode(ResponseCode.SUCCESS);
            response.setRetdesc("上传成功");
        }catch (Exception e){
            e.printStackTrace();
            response.setRetcode(ResponseCode.FAILED);
            response.setRetdesc("上传失败");
        }
        return response;
    }
}

重启项目之后,就可以访问各个接口

springboot配置事务

springboot配置事务有两种方式

1、在SpringbootdemoApplication.java项目入口,添加@EnableTransactionManagement的注解用来开启事务

2、在service实现类上添加@Transactional注解,那么该类的所有方法都进行事务管理;也可以直接在service实现类的方法上直接添加@Transactional注解,那么只对该方法进行事务管理,上面代码中有对方法添加事务的例子

springboot打包进行tomcat部署

Edit Configuration -> Maven -> 添加 ->启动 -> 复制war包 -> tomcat webapp ->修改war包的名字 -> tomcat bin -> startup.bat

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值