SpringBoot整合Mybatis-plus实现商品推荐

1. 准备工作

在开始编写代码之前,我们需要准备一下环境:

  • Java 8+
  • IntelliJ IDEA
  • Node.js 和 npm
  • Vue CLI

如果你还没有安装Vue CLI,则可以使用以下命令在终端中安装:

npm install -g @vue/cli

2. 创建Spring Boot项目

首先,我们需要使用Spring Boot创建一个新项目。在IntelliJ IDEA中,选择“New Project”,然后选择“Spring Initializr”。

在“New Project”窗口中,选择“Spring Initializr”,并填写以下信息:

  • Group:com.example
  • Artifact:spring-boot-mybatis-plus-demo
  • Dependencies:选择“Web”,“MyBatis-Plus”和“MySQL Driver”

点击“Next”确认,并在下一个窗口接受默认值。最后,点击“Finish”完成创建项目。

3. 创建MySQL数据库

我们需要创建一个MySQL数据库来存储我们的商品数据。在这个示例中,我们将创建一个名为“product”的数据库和一个名为“product”表的数据表。

首先,打开MySQL控制台,并运行以下命令来创建数据库:

CREATE DATABASE product;

接下来,我们需要创建一个数据表。使用以下命令创建一个名为“product”的数据表:

CREATE TABLE product (
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(255) DEFAULT NULL,
  price decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

在此示例中,我们只需要包含商品名称和价格两个字段。如果您要构建更实际的使用案例,则可以添加更多的字段。

4. 配置MyBatis-Plus

我们需要添加MyBatis-Plus的依赖,这里我们在pom.xml文件中加入以下代码:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.2</version>
</dependency>

在这个示例中,我们没有使用MyBatis,而是使用MyBatis-Plus。MyBatis-Plus是一个集成了许多MyBatis功能,并且简化了使用的库。

接下来,在application.properties中添加以下代码,配置数据库连接:

spring.datasource.url=jdbc:mysql://localhost:3306/product?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

mybatis-plus.mapper-locations=classpath:/mapper/**/*.xml

这里我们使用了MySQL数据库,如果您的数据库不同,请修改连接URL、用户名和密码。

5. 编写Product实体类

为了让MyBatis-Plus知道如何映射我们的数据库表,我们需要创建一个Product实体类。在这个示例中,Product实体类包含三个字段:id、name和price。

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Product {
    private Long id;
    private String name;
    private BigDecimal price;
}

在这里,我们使用了Lombok注解@Data,可以自动生成getter和setter方法,@NoArgsConstructor和@AllArgsConstructor可以生成无参和全参构造器。

6. 创建ProductMapper

接下来,我们将创建一个ProductMapper,用于实现一些操作数据库的方法。在这个示例中,我们将编写一些包括查询所有商品、根据商品名模糊查询、新增商品、更新商品和删除商品的方法。

使用MyBatis-Plus,我们只需要继承BaseMapper就可以实现以上的操作,例如:

public interface ProductMapper extends BaseMapper<Product> {
}

7. 配置Swagger

Swagger是一个流行的API文档工具,我们可以使用Swagger来记录和调试我们的API,方便前端调用接口。在这个示例中,我们使用Swagger 2.0版本。

添加Swagger的依赖:

<!-- Swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>3.0.0</version>
</dependency>
<!-- Swagger UI -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>3.0.0</version>
</dependency>

在Spring Boot的主类上添加@EnableSwagger2注解,开启Swagger的支持:

@EnableSwagger2
@SpringBootApplication
public class SpringBootMybatisPlusDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootMybatisPlusDemoApplication.class, args);
    }
}

在SwaggerConfig.java文件中配置Swagger,示例代码如下:

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.product.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot集成MyBatis-Plus实现商品推荐")
                .description("利用Swagger UI查看和调试接口")
                .termsOfServiceUrl("http://localhost:8080/")
                .version("1.0")
                .build();
    }
}

8. 编写商品Controller

我们需要创建一个ProductController类,用于实现与商品相关的API。在这个示例中,我们将编写一些包括查询所有商品、根据商品名模糊查询、新增商品、更新商品和删除商品的API。

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    @ApiOperation(value = "获取所有商品列表")
    @GetMapping("/getAll")
    public List<Product> getAllProducts() {
        return productService.getAllProducts();
    }

    @ApiOperation(value = "根据商品名模糊查询")
    @GetMapping("/{name}")
    public List<Product> getProductsByName(@PathVariable String name) {
        return productService.getProductsByName(name);
    }

    @ApiOperation(value = "新增商品")
    @PostMapping("")
    public boolean addProduct(@RequestBody Product product) {
        return productService.addProduct(product);
    }

    @ApiOperation(value = "更新商品信息")
    @PutMapping("/{id}")
    public boolean updateProduct(@PathVariable Long id, @RequestBody Product product) {
        return productService.updateProduct(id, product);
    }

    @ApiOperation(value = "删除商品")
    @DeleteMapping("/{id}")
    public boolean deleteProduct(@PathVariable Long id) {
        return productService.deleteProduct(id);
    }
}

在这里,我们使用了Swagger注解@ApiOperation来描述API,方便接口文档的编写。

9. 编写商品Service

我们需要创建一个ProductService类,用于调用MyBatis-Plus操作数据库。在这个示例中,我们实现了从数据库中查询所有商品、根据商品名模糊查询、新增商品、更新商品和删除商品的方法。

@Service
public class ProductService {
    @Autowired
    private ProductMapper productMapper;

    public List<Product> getAllProducts() {
        return productMapper.selectList(null);
    }

    public List<Product> getProductsByName(String name) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return productMapper.selectList(queryWrapper);
    }

    public boolean addProduct(Product product) {
        return productMapper.insert(product) > 0;
    }

    public boolean updateProduct(Long id, Product product) {
        product.setId(id);
        return productMapper.updateById(product) > 0;
    }

    public boolean deleteProduct(Long id) {
        return productMapper.deleteById(id) > 0;
    }
}

10. 整合Vue和Element-UI

接下来,我们将使用Vue结合Element-UI的组件进行调用后端接口。首先,我们使用Vue CLI创建一个新的Vue项目:

vue create product-vue

然后在命令行中运行以下命令来安装Element-UI和Axios:

npm install element-ui --save
npm install axios

在完成安装后,我们可以开始创建Vue组件。在src/components目录下创建一个新文件ProductList.vue,代码如下:

<template>
  <div>
    <el-input v-model="searchName" placeholder="请输入搜索关键字" class="search-input"></el-input>
    <el-button type="primary" @click="searchProducts">搜索</el-button>
    <el-button type="default" class="add-btn" @click="showAddDialog=true">新增商品</el-button>
    <el-dialog title="新增商品" :visible.sync="showAddDialog">
      <el-form :model="newProduct" label-position="right">
        <el-form-item label="商品名称">
          <el-input v-model="newProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="newProduct.price" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addProduct">确定</el-button>
        <el-button @click="showAddDialog=false">取消</el-button>
      </div>
    </el-dialog>
    <el-table :data="products" stripe style="width: 100%">
      <el-table-column type="index" width="50" label="序号"></el-table-column>
      <el-table-column prop="name" label="商品名称"></el-table-column>
      <el-table-column prop="price" label="价格"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" type="primary" @click="editProduct(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑商品" :visible.sync="showEditDialog">
      <el-form :model="currentProduct" label-position="right">
        <el-form-item label="商品名称">
          <el-input v-model="currentProduct.name"></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="currentProduct.price" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updateProduct">确定</el-button>
        <el-button @click="showEditDialog=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Message, Dialog, Form, FormItem, Input, Button, Table, TableColumn } 
  from "element-ui";

export default {
  name: "ProductList",
  components: { ElDialog: Dialog, ElForm: Form, ElFormItem: FormItem, 
    ElInput: Input, ElButton: Button, ElTable: Table, ElTableColumn: TableColumn },
  data() {
    return {
      products: [],
      searchName: '',
      showAddDialog: false,
      newProduct: { name: '', price: null },
      currentProduct: null,
      showEditDialog: false,
      editProductIndex: -1
    }
  },
  created() {
    this.loadProducts();
  },
  methods: {
    loadProducts() {
      axios.get('/product/getAll').then((response) => {
        this.products = response.data;
      }).catch((error) => {
        console.error(error);
        Message.error('加载商品列表失败');
      });
    },
    searchProducts() {
      axios.get('/product/' + this.searchName).then((response) => {
        this.products = response.data;
      }).catch((error) => {
        console.error(error);
        Message.error('搜索商品失败');
      });
    },
    addProduct() {
      axios.post('/product', this.newProduct).then((response) => {
        this.showAddDialog = false;
        this.loadProducts();
        Message.success('新增商品成功');
      }).catch((error) => {
        console.error(error);
        Message.error('新增商品失败');
      });
    },
    editProduct(product) {
      this.currentProduct = Object.assign({}, product);
      this.editProductIndex = this.products.indexOf(product);
      this.showEditDialog = true;
    },
    updateProduct() {
      axios.put('/product/' + this.currentProduct.id, this.currentProduct).then((response) => {
        this.showEditDialog = false;
        this.loadProducts();
        Message.success('更新商品成功');
      }).catch((error) => {
        console.error(error);
        Message.error('更新商品失败');
      });
    },
    deleteProduct(product) {
      this.$confirm('确定要删除该商品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete('/product/' + product.id).then((response) => {
          Message.success('删除成功');
          this.loadProducts();
        }).catch((error) => {
          console.error(error);
          Message.error('删除商品失败');
        });
      }).catch(() => {
        Message.info('已取消删除');
      });
    }
  }
};
</script>

<style scoped>
.search-input {
  width: 300px;
  margin-right: 10px;
}
.add-btn {
  margin: 0 10px;
}
</style>

在这里,我们使用了Element-UI的组件,包括Input、Button、Table、Dialog和Form等,用于实现前端的逻辑。同时,我们使用了Axios来调用后端接口,实现数据的读写操作。

11. 运行程序

在完成以上工作后,我们就可以运行程序来测试它是否正常工作了。首先,在终端中进入Spring Boot项目目录,并运行以下命令:

mvn spring-boot:run

然后,在另一个终端中进入Vue项目目录,并运行以下命令:

npm run serve

现在,在浏览器中打开http://localhost:8081(Vue项目的默认端口),即可访问我们的页面。

12. 结语

在本文中,我们介绍了如何使用Spring Boot整合MyBatis-Plus实现商品推荐,并使用Vue结合Element-UI的组件进行调用接口。希望这篇文章能够对您有所帮助,谢谢阅读!

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

沙漠真有鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值