你可以使用一個連接表,以避免分類彙總這樣的根源:
@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'正在朝着錯誤的方向前進,因爲將兩個總計關聯到同一個事務 –