这个问题在这里已经以多种形式提出,但似乎没有一个解决方案对我有用。我正在尝试删除父实体,并且希望同时删除所有子实体。
我的实体:
@Entity
@Table(name = "item", catalog = "myshchema")
public class Item implements java.io.Serializable {
@JoinColumn(name = "item_id", insertable = false, updatable = false, nullable = false)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ItemCategory> categories;
/* Getters and Setters and other fields*/
}
项目表:
CREATE TABLE `item` (
`item_id` int(11) NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
PRIMARY KEY (`item_id`),
UNIQUE KEY `item_id_UNIQUE` (`item_id`),
KEY `FK_ITEM_STORE_ID_idx` (`store_id`),
CONSTRAINT `FK_ITEM_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `store` (`store_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8;
而我的另一个实体
@Entity
@Table(name = "item_category", catalog = "myschema")
@IdClass(ItemCategoryIndex.class)
public class ItemCategory implements java.io.Serializable {
@Id
@Column(name = "category_id", unique = true, nullable = false, insertable = false, updatable = false)
private Integer categoryId;
@Id
private Store store;
@Id
private Item item;
@Id
private String categoryName;
/* Getters and Setters */
}
项目类别表:
CREATE TABLE `item_category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`store_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`category_name` varchar(45) NOT NULL,
PRIMARY KEY (`category_id`),
UNIQUE KEY `category_id_UNIQUE` (`category_id`),
UNIQUE KEY `IDX_UNIQUE_STORE_CATEGORY` (`store_id`,`item_id`,`category_name`) USING BTREE,
KEY `FK_CATEGORY_STORE_ID_idx` (`store_id`),
KEY `FK_ITEM_CATEGORY_ID_idx` (`item_id`),
CONSTRAINT `FK_CATEGORY_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `store` (`store_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_ITEM_CATEGORY_ID` FOREIGN KEY (`item_id`) REFERENCES `item` (`item_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=162 DEFAULT CHARSET=utf8;
我试着这样删除该项目:
Item item = entityManager.find(Item.class, idList.get(i));
entityManager.remove(item);
我的日志显示Hibernate试图将ItemCategory的主键设置为null:
Hibernate: update myschema.item_category set item_id=null where item_id=?
ERROR o.h.e.jdbc.spi.SqlExceptionHelper.logExceptions 146 - Column 'item_id' cannot be null
我甚至尝试循环遍历子记录并手动删除它们,但Hibernate仍然会对null查询进行此更新。我做错了什么?
2条答案
按热度按时间cotxawn71#
我得把你的问题分成两部分
首先,让我们讨论一下数据库模式设计。
根据您的模式,
item
和item_category
具有一对多关系,这意味着一个项目可以具有/被分配给不同的类别,但不同的项目不能具有/被分配给相同的类别。这完全没问题如果这确实是您的业务需求,我提到它是因为它对我来说没有意义,而且这种情况很少发生。
如果你想要的是一个类别可以有多个项目,反之亦然,
item
和item_category
必须是一个多对多关系。需要另外有一个join table。其次-假设模式不变
ItemCategory
是关系的所有者,因为它有一个指向item
表的外键item_id
。所以ItemCategoy应该看起来大致如下:您的
Item
实体将大致如下所示:要从
Item
中删除所有子实体(ItemCategory
),只需em.remove(item);
orphanRemoval
是true
,删除父节点,子节点也会被删除。mspsb9vt2#
在Hibernate中,您需要决定谁拥有关系。如果你让父端(ItemCategory)拥有关系,你会发现Item+ ItemCategory的插入/删除将涉及ItemCategory表中item_id的更新(这是我从你的异常中观察到的)。在大多数情况下,这不是优选。我们通常让孩子们自己的关系。这是通过使用mappedBy完成的
(伪代码)
这里的诀窍是mappedBy