Spring Boot是一个简化Spring开发的框架。用来监护spring应用开发,约定大于配置,去繁就简,just run 就能创建一个独立的,产品级的应用。

我们在使用Spring Boot时只需要配置相应的Spring Boot就可以用所有的Spring组件,简单的说,spring boot就是整合了很多优秀的框架,不用我们自己手动的去写一堆xml配置然后进行配置。从本质上来说,Spring Boot就是Spring,它做了那些没有它你也会去做的Spring Bean配置。

1.新建一个项目

依次点击 > 文件 > 新建 > 项目 如下图:

springboot多表联合查询 springboot查询两个表所有数据_java

选择Spring Initializr项目        注意:创建springboot项目时需要网络 

  1. 按自己的意愿打自己的项目名称
  2. 选择项目要存放的位置
  3. 类型选择Maven
  4. 语言选择Java
  5. 组一般是com.x x可以按自己喜欢的方式修改
  6. 工件就是项目名称
  7. 软件包名称跟组一样
  8. 项目SDK选择 1.8
  9. java选择8
  10. 打包方式为jar

springboot多表联合查询 springboot查询两个表所有数据_intellij-idea_02

选择项目需要的依赖

首先选择Developer Tools选择Lombok,再点击web选择Spring Web,以及SQL下的Mybatis Framework和MySQL Driver

springboot多表联合查询 springboot查询两个表所有数据_springboot多表联合查询_03

 首次创建springboot项目会加载一段时间

2.查看项目新建完成后的pom文件

<?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 https://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.7.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.p</groupId>
    <artifactId>springboot-CRUD</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-CRUD</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-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

3.修改配置文件src/main/resources

修改配置文件本文不使用application.properties文件而使用更加简洁的application.yml文件

springboot多表联合查询 springboot查询两个表所有数据_spring_04

在application.yml文件里面加入以下内容:

server:
  port: 8989 #指定接口
  servlet:
    context-path: /springboot-CRUD #指定项目名

spring:
  #整合mybatis相关配置
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/ems-jsp?serverTimezone=UTC
    username: root
    password: root

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

#配置日志
logging:
  level:
    root: info #调整全局日志展示debug
    com.p: debug #输出指定包的日志级别

4.创建表

-- ----------------------------
-- Table structure for goods
-- ----------------------------
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods`  (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `goodsName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `goodsPrice` decimal(10, 2) NOT NULL,
  `goodsNum` int(11) NOT NULL,
  `goodsType` int(255) NOT NULL,
  `remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`id`) USING BTREE,
  INDEX `goodsType`(`goodsType`) USING BTREE,
  CONSTRAINT `goods_ibfk_1` FOREIGN KEY (`goodsType`) REFERENCES `type` (`typeid`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of goods
-- ----------------------------
INSERT INTO `goods` VALUES (1, '娃哈哈', 12.00, 4, 1, '好喝的饮料');

-- ----------------------------
-- Table structure for type
-- ----------------------------
DROP TABLE IF EXISTS `type`;
CREATE TABLE `type`  (
  `typeId` int(11) NOT NULL,
  `typeName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  PRIMARY KEY (`typeId`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of type
-- ----------------------------
INSERT INTO `type` VALUES (1, '零食类');
INSERT INTO `type` VALUES (2, '水果类');
INSERT INTO `type` VALUES (3, '蔬菜类');

5.该项目的文件结构

springboot多表联合查询 springboot查询两个表所有数据_spring_05

 

6.开始编码操作

6.1在entity包中新建Goods.java,使之与数据库中的字段一一对应

     @Data注解可以省略getset,用这个注解就能实现

@Data
public class Goods {
    private Integer id; //商品序号
    private String goodsName;  //商品名称
    private double goodsPrice; //商品价格
    private Integer goodsNum;  //商品数量
    private Integer goodsType; //商品类型
    private String remark;  //商品描述
    private String typeName;//商品类型名称
}

6.2 在dao包中创建GoodsDao接口

@Mapper
public interface GoodsDao {
    /**
     * 商品信息查询
     */
    List<Goods> GoodsList();

    /**
     * 添加商品信息
     * @param goods
     */
    void addGoods(Goods goods);

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    Goods idByGoods(Integer id);

    /**
     * 修改商品信息
     * @param goods
     */
    void updateGoods(Goods goods);

    /**
     * 根据id删除商品信息
     * @param id
     */
    void deleteGoods(Integer id);
}

6.3在service包中创建GoodsService.java

public interface GoodsService {
    /**
     * 商品信息查询
     */
    List<Goods> GoodsList();

    /**
     * 添加商品信息
     * @param goods
     */
    void addGoods(Goods goods);

    /**
     * 根据id查询商品信息
     * @param id
     * @return
     */
    Goods idByGoods(Integer id);

    /**
     * 修改商品信息
     * @param goods
     */
    void updateGoods(Goods goods);

    /**
     * 根据id删除商品信息
     * @param id
     */
    void deleteGoods(Integer id);
}

6.4在service包中创建GoodsServiceImpl.java

@Service
public class GoodsServiceImpl implements GoodsService{

    @Autowired
    private GoodsDao goodsDao;

    @Override
    public List<Goods> GoodsList() {
        return goodsDao.GoodsList();
    }

    @Override
    public void addGoods(Goods goods) {
        goodsDao.addGoods(goods);
    }

    @Override
    public Goods idByGoods(Integer id) {
        return goodsDao.idByGoods(id);
    }

    @Override
    public void updateGoods(Goods goods) {
        goodsDao.updateGoods(goods);
    }

    @Override
    public void deleteGoods(Integer id) {
        goodsDao.deleteGoods(id);
    }
}

6.5在util包中创建R.java以及ResultCodeEnum.java

@Data
public class R {

    //状态值
    private Boolean success;

    //状态吗
    private Integer code;

    //数据
    private String message;

    private Map<String, Object> data = new HashMap<String, Object>();

    private R(){}

    public static R ok(){
        R r = new R();
        r.setSuccess(ResultCodeEnum.SUCCESS.getSuccess());
        r.setCode(ResultCodeEnum.SUCCESS.getCode());
        r.setMessage(ResultCodeEnum.SUCCESS.getMessage());
        return r;
    }

    public static R error(){
        R r = new R();
        r.setSuccess(ResultCodeEnum.UNKNOWN_REASON.getSuccess());
        r.setCode(ResultCodeEnum.UNKNOWN_REASON.getCode());
        r.setMessage(ResultCodeEnum.UNKNOWN_REASON.getMessage());
        return r;
    }

    public static R setResult(ResultCodeEnum resultCodeEnum){
        R r = new R();
        r.setSuccess(resultCodeEnum.getSuccess());
        r.setCode(resultCodeEnum.getCode());
        r.setMessage(resultCodeEnum.getMessage());
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }

}
@Getter
public enum ResultCodeEnum {

    SUCCESS(true, 20000,"成功"),
    UNKNOWN_REASON(false, 20001, "未知错误"),
    BAD_SQL_GRAMMAR(false, 21001, "sql语法错误"),
    JSON_PARSE_ERROR(false, 21002, "json解析异常"),
    PARAM_ERROR(false, 21003, "参数不正确"),
    FILE_UPLOAD_ERROR(false, 21004, "文件上传错误"),
    EXCEL_DATA_IMPORT_ERROR(false, 21005, "Excel数据导入错误"),
    USERLOGIN_INVALID_ERROR(false, 21007,"登录信息过期,请重新登录"),
    USERUNLOGIN_ERROR(false, 21008,"用户未登录,请重新登录");

    private Boolean success;

    private Integer code;

    private String message;

    private ResultCodeEnum(Boolean success, Integer code, String message) {
        this.success = success;
        this.code = code;
        this.message = message;
    }
}

6.6在controller包中创建GoodsServiceImpl.java

@Controller
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/getAll")
    @ResponseBody //以json 格式返回数据
    public R getAll(){
        List<Goods> all=goodsService.GoodsList();
        return R.ok().code(200).data("goodsList",all);
    }

    @RequestMapping("/deleteGoods")
    @ResponseBody //以json 格式返回数据
    public R deleteGoods(@RequestParam("id")Integer id){
        goodsService.deleteGoods(id);
        return R.ok().data("istrue",id);
    }

    @RequestMapping("/getById")
    @ResponseBody //以json 格式返回数据
    public R getById(@RequestParam("id")Integer id){
        goodsService.idByGoods(id);
        return R.ok().data("user",id);
    }

    @RequestMapping("/updateGoods")
    @ResponseBody //以json 格式返回数据
    public R updateGoods(Goods goods){
        goodsService.updateGoods(goods);
        return R.ok().data("goods",goods);
    }

    @RequestMapping("/addGoods")
    @ResponseBody //以json 格式返回数据
    public R addGoods(Goods goods){
        goodsService.addGoods(goods);
        return R.ok().data("goods",goods);
    }
}

6.7在src/main/resources/com/p/mapper文件夹下新建GoodsDao的映射文件GoodsMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.p.dao.GoodsDao">
    <!--商品列表-->
    <select id="GoodsList" resultType="Goods">
        select * from goods s,type b where s.goodsType=b.typeId
    </select>

    <!--添加商品信息-->
    <insert id="addGoods" parameterType="Goods" useGeneratedKeys="true" keyProperty="id">
        insert into `goods` values (#{id},#{goodsName},#{goodsPrice},#{goodsNum},#{goodsType},#{remark});
    </insert>

    <!--根据id查询一个员工信息-->
    <select id="idByGoods" parameterType="Integer" resultType="Goods">
        select * from goods where id=#{id}
    </select>

    <!--更新员工信息-->
    <update id="updateGoods" parameterType="Goods">
        update `goods` set goodsName=#{goodsName},goodsPrice=#{goodsPrice},goodsNum=#{goodsNum},goodsType=#{goodsType},remark=#{remark}
        where id=#{id}
    </update>

    <!--根据id删除员工信息-->
    <delete id="deleteGoods" parameterType="Integer">
        delete from `goods` where id=#{id}
    </delete>
</mapper>

7.测试

到这里就完成了增删改查操作,接下来我们对上面的代码在Postman中进行验证

7.1查询商品信息:

springboot多表联合查询 springboot查询两个表所有数据_spring boot_06

 

springboot多表联合查询 springboot查询两个表所有数据_java_07

 7.2根据id删除商品信息

springboot多表联合查询 springboot查询两个表所有数据_java_08

  7.3新增商品信息

springboot多表联合查询 springboot查询两个表所有数据_intellij-idea_09

  7.4根据id查询商品信息

springboot多表联合查询 springboot查询两个表所有数据_springboot多表联合查询_10

  7.4根据id修改商品信息

springboot多表联合查询 springboot查询两个表所有数据_spring_11