1. 準備工作
在開始編寫代碼之前,我們需要準備一下環(huán)境:
- Java 8+
- IntelliJ IDEA
- Node.js 和 npm
- Vue CLI
如果你還沒有安裝Vue CLI,則可以使用以下命令在終端中安裝:
npm install -g @vue/cli
2. 創(chuàng)建Spring Boot項目
首先,我們需要使用Spring Boot創(chuàng)建一個新項目。在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”完成創(chuàng)建項目。
3. 創(chuàng)建MySQL數(shù)據(jù)庫
我們需要創(chuàng)建一個MySQL數(shù)據(jù)庫來存儲我們的商品數(shù)據(jù)。在這個示例中,我們將創(chuàng)建一個名為“product”的數(shù)據(jù)庫和一個名為“product”表的數(shù)據(jù)表。
首先,打開MySQL控制臺,并運行以下命令來創(chuàng)建數(shù)據(jù)庫:
CREATE DATABASE product;
接下來,我們需要創(chuàng)建一個數(shù)據(jù)表。使用以下命令創(chuàng)建一個名為“product”的數(shù)據(jù)表:
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;
在此示例中,我們只需要包含商品名稱和價格兩個字段。如果您要構(gòu)建更實際的使用案例,則可以添加更多的字段。
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中添加以下代碼,配置數(shù)據(jù)庫連接:
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數(shù)據(jù)庫,如果您的數(shù)據(jù)庫不同,請修改連接URL、用戶名和密碼。
5. 編寫Product實體類
為了讓MyBatis-Plus知道如何映射我們的數(shù)據(jù)庫表,我們需要創(chuàng)建一個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可以生成無參和全參構(gòu)造器。
6. 創(chuàng)建ProductMapper
接下來,我們將創(chuàng)建一個ProductMapper,用于實現(xiàn)一些操作數(shù)據(jù)庫的方法。在這個示例中,我們將編寫一些包括查詢所有商品、根據(jù)商品名模糊查詢、新增商品、更新商品和刪除商品的方法。
使用MyBatis-Plus,我們只需要繼承BaseMapper就可以實現(xiàn)以上的操作,例如:
public interface ProductMapper extends BaseMapper<Product> {
}
7. 配置Swagger
Swagger是一個流行的API文檔工具,我們可以使用Swagger來記錄和調(diào)試我們的API,方便前端調(diào)用接口。在這個示例中,我們使用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實現(xiàn)商品推薦")
.description("利用Swagger UI查看和調(diào)試接口")
.termsOfServiceUrl("http://localhost:8080/")
.version("1.0")
.build();
}
}
8. 編寫商品Controller
我們需要創(chuàng)建一個ProductController類,用于實現(xiàn)與商品相關(guān)的API。在這個示例中,我們將編寫一些包括查詢所有商品、根據(jù)商品名模糊查詢、新增商品、更新商品和刪除商品的API。
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductService productService;
@ApiOperation(value = "獲取所有商品列表")
@GetMapping("/getAll")
public List<Product> getAllProducts() {
return productService.getAllProducts();
}
@ApiOperation(value = "根據(jù)商品名模糊查詢")
@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
我們需要創(chuàng)建一個ProductService類,用于調(diào)用MyBatis-Plus操作數(shù)據(jù)庫。在這個示例中,我們實現(xiàn)了從數(shù)據(jù)庫中查詢所有商品、根據(jù)商品名模糊查詢、新增商品、更新商品和刪除商品的方法。
@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結(jié)合Element-UI的組件進行調(diào)用后端接口。首先,我們使用Vue CLI創(chuàng)建一個新的Vue項目:
vue create product-vue
然后在命令行中運行以下命令來安裝Element-UI和Axios:
npm install element-ui --save
npm install axios
在完成安裝后,我們可以開始創(chuàng)建Vue組件。在src/components目錄下創(chuàng)建一個新文件ProductList.vue,代碼如下:
<template>
<div>
<el-input v-model="searchName" placeholder="請輸入搜索關(guān)鍵字" 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等,用于實現(xiàn)前端的邏輯。同時,我們使用了Axios來調(diào)用后端接口,實現(xiàn)數(shù)據(jù)的讀寫操作。
11. 運行程序
在完成以上工作后,我們就可以運行程序來測試它是否正常工作了。首先,在終端中進入Spring Boot項目目錄,并運行以下命令:
mvn spring-boot:run
然后,在另一個終端中進入Vue項目目錄,并運行以下命令:
npm run serve
現(xiàn)在,在瀏覽器中打開http://localhost:8081(Vue項目的默認端口),即可訪問我們的頁面。文章來源:http://www.zghlxwxcb.cn/news/detail-430134.html
12. 結(jié)語
在本文中,我們介紹了如何使用Spring Boot整合MyBatis-Plus實現(xiàn)商品推薦,并使用Vue結(jié)合Element-UI的組件進行調(diào)用接口。希望這篇文章能夠?qū)δ兴鶐椭x謝閱讀!文章來源地址http://www.zghlxwxcb.cn/news/detail-430134.html
到了這里,關(guān)于SpringBoot整合Mybatis-plus實現(xiàn)商品推薦的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!