基于commodity(cid,cname,cstyle,cprice),user(uid,uname,upwd),cart(cartid,uid,cid,cartprice,cartselected),order(oid,uid,cid,oprice,ocondition)四个表,使用springboot+maven 完成电商网站的商品搜索功能
时间: 2023-09-14 08:07:19 浏览: 113
首先需要创建四个实体类,分别对应四个表的结构,并且使用JPA注解进行映射。例如:
Commodity实体类:
```java
@Entity
@Table(name = "commodity")
public class Commodity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cid;
private String cname;
private String cstyle;
private BigDecimal cprice;
// 省略getter和setter方法
}
```
User实体类:
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long uid;
private String uname;
private String upwd;
// 省略getter和setter方法
}
```
Cart实体类:
```java
@Entity
@Table(name = "cart")
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long cartid;
private Long uid;
private Long cid;
private BigDecimal cartprice;
private Boolean cartselected;
// 省略getter和setter方法
}
```
Order实体类:
```java
@Entity
@Table(name = "order")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long oid;
private Long uid;
private Long cid;
private BigDecimal oprice;
private Integer ocondition;
// 省略getter和setter方法
}
```
接下来,需要创建对应的Repository接口,实现对四个表的增删改查操作。例如:
CommodityRepository:
```java
public interface CommodityRepository extends JpaRepository<Commodity, Long> {
List<Commodity> findByCnameContaining(String keyword);
List<Commodity> findByCstyleContaining(String keyword);
List<Commodity> findByCnameContainingOrCstyleContaining(String keyword1, String keyword2);
}
```
UserRepository:
```java
public interface UserRepository extends JpaRepository<User, Long> {
User findByUname(String uname);
}
```
CartRepository:
```java
public interface CartRepository extends JpaRepository<Cart, Long> {
List<Cart> findByUid(Long uid);
List<Cart> findByCid(Long cid);
Cart findByUidAndCid(Long uid, Long cid);
}
```
OrderRepository:
```java
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByUid(Long uid);
List<Order> findByCid(Long cid);
}
```
最后,需要创建Controller类,处理前端请求,并调用对应的Repository接口实现搜索功能。例如:
```java
@RestController
@RequestMapping("/search")
public class SearchController {
@Autowired
private CommodityRepository commodityRepository;
@GetMapping("/commodity")
public List<Commodity> searchCommodity(@RequestParam("keyword") String keyword) {
return commodityRepository.findByCnameContainingOrCstyleContaining(keyword, keyword);
}
// 省略其他搜索方法
}
```
这样就完成了电商网站的商品搜索功能。前端可以通过调用接口获取搜索结果。例如,调用 `http://localhost:8080/search/commodity?keyword=手机` 就可以获取所有商品名或商品类型含有“手机”关键字的商品。
阅读全文