一上渴、背景
本文章屬于系列文章,背景請(qǐng)前往系列入口文章
本篇介紹spring boot項(xiàng)目中,上篇說(shuō)明了一對(duì)多的查詢,本篇講述如何做多對(duì)多的兩個(gè)表的數(shù)據(jù)結(jié)構(gòu)的查詢
具體請(qǐng)看github項(xiàng)目的third分支
二惰拱、上手
2.1 說(shuō)明
SQL文件(接上篇):
DROP TABLE IF EXISTS `cart`;
CREATE TABLE `cart` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `cart_item`;
CREATE TABLE `cart_item` (
`cart_id` int(11) unsigned NOT NULL,
`item_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`item_id`, `cart_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
insert into cart_item (cart_id, item_id) values (1, 3);
insert into cart_item (cart_id, item_id) values (1, 4);
新增了cart
和cart_item
表,cart和item表是多對(duì)多的關(guān)系确垫。
cart_item
存儲(chǔ)cart和item的id對(duì)應(yīng)關(guān)系弓颈。
2.2 新增CartController
@RestController
public class CartController {
@Autowired
private CartRepository cartRepository;
@GetMapping("/cart/{id}")
public CartEntity findById(@PathVariable Integer id) {
return cartRepository.findById(id).get();
}
}
同時(shí)新增CartEntity:
@Entity
@Data
@Table(name = "cart")
public class CartEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable(name = "cart_item", joinColumns = {
@JoinColumn(name = "cart_id", referencedColumnName = "id")}, inverseJoinColumns = {
@JoinColumn(name = "item_id", referencedColumnName = "id")})
private List<ItemEntity> items;
}
我們利用表cart_item
關(guān)聯(lián)了cart
表和item
表,測(cè)試成功:
(完)