你可以使用一个连接表,以避免分类汇总这样的根源:
@Entity
public class Product {
@Id
@GeneratedValue
private int id;
@OneToMany
@JoinTable
private Set<Category> categories;
// constructor, getters, setters, etc...
}
@Entity
public class Category {
@Id
@GeneratedValue
private int id;
// constructor, getters, setters, etc...
}
只是作为一个例子,我会插在一起的几个:
for (int n = 0; n < 3; ++n) {
categoryRepository.save(new Category());
}
Set<Category> categories = categoryRepository.findAll();
productRepository.save(new Product(categories));
,这导致以下(你没有指定你的DBMS,所以我只是假设...)MySQL:
MariaDB [so41336455]> show tables;
+----------------------+
| Tables_in_so41336455 |
+----------------------+
| category |
| product |
| product_categories |
+----------------------+
3 rows in set (0.00 sec)
MariaDB [so41336455]> describe category; describe product; describe product_categories;
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.00 sec)
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.00 sec)
+---------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| product_id | int(11) | NO | PRI | NULL | |
| categories_id | int(11) | NO | PRI | NULL | |
+---------------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)
和cour瑟毫不奇怪相对于它们的内容:
MariaDB [so41336455]> select * from category; select * from product; select * from product_categories;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
+----+
3 rows in set (0.00 sec)
+----+
| id |
+----+
| 1 |
+----+
1 row in set (0.00 sec)
+------------+---------------+
| product_id | categories_id |
+------------+---------------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
+------------+---------------+
3 rows in set (0.00 sec)
另外我想避免当你使用关系数据库存储在一个逗号分隔的列表关系。它导致不健康的数据库设计,并会导致您在某个时候头痛。
'级联= CascadeType.ALL'正在朝着错误的方向前进,因为将两个总计关联到同一个事务 –