@OneToMany删除子项

时间:2017-09-22 11:06:22

标签: java spring hibernate

我有两个这样的实体:

public class Client {
  ...
@OneToMany(mappedBy = "client", cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.REMOVE },orphanRemoval = true, fetch=FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
@Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.DELETE_ORPHAN })
private List<CompanyContract> companyContracts;
  ...
}

CompanyContract:

public class CompanyContract {

...

@ManyToOne
@JoinColumn(name = "IDCLIENT")
private Client client;

...
}

我想删除像这样的companyContract:

client.getCompanyContracts().remove(companyContract)
client = clientService.updateClient(client);

但删除过程没有发生

我做错了什么?

编辑

这是我的DAO中的updateClient方法:

@Override
@Transactional
public Client updateClient(Client client) {

    return entityManager.merge(client);
}

3 个答案:

答案 0 :(得分:1)

首先,您不需要设置minikube startcascadeTypes。我认为这可能是你问题的根源。

@Cascade中的override equalshashCode了吗?因为您可能没有从ContractCompany

中删除所需的对象

看看这个

List<ContactCompany>

@OneToMany(mappedBy = "client", ...) 通知hibernate客户端是此关系的所有者,因此您需要获取mappedBy,获取client列表,删除一个(确保将其从列表中删除),更新客户端并删除对象。

以下示例源代码

clientContracts

保存两个对象,CompanyContract toBeRemoved = //companyContract which you want to delete client.getCompanyContracts().remove(toBeRemoved); toBeRemoved.client = null; toBeRemoved

答案 1 :(得分:0)

尝试使用这些注释:

@OneToMany(mappedBy = "client", cascade = CascadeType.ALL,orphanRemoval = true, fetch=FetchType.EAGER)
private List<CompanyContract> companyContracts;

答案 2 :(得分:0)

Cascade delete-orphan示例 如果您只想删除两个引用的'stockDailyRecords'记录?这称为孤儿删除,请参见示例...

1. No delete-orphan cascade
You need to delete the ‘stockDailyRecords’ one by one.

StockDailyRecord sdr1 = (StockDailyRecord)session.get(StockDailyRecord.class,
                                            new Integer(56));
StockDailyRecord sdr2 = (StockDailyRecord)session.get(StockDailyRecord.class,
                                            new Integer(57));

session.delete(sdr1);
session.delete(sdr2);
Output

Hibernate:
    delete from mkyong.stock_daily_record
    where DAILY_RECORD_ID=?
Hibernate:
    delete from mkyong.stock_daily_record
    where DAILY_RECORD_ID=?
  1. 使用delete-orphan级联 在“stockDailyRecords”中声明了cascade =“delete-orphan”以启用删除孤立级联效果。当您保存或更新股票时,它将删除那些已经标记为已删除的'stockDailyRecords'。

    Stock stock = (Stock)session.get(Stock.class, new Integer(2));
    stock.getStockDailyRecords().remove(sdr1);
    stock.getStockDailyRecords().remove(sdr2);
    
    session.saveOrUpdate(stock);
    

    输出

    休眠:     从mkyong.stock_daily_record中删除     DAILY_RECORD_ID =? 休眠:     从mkyong.stock_daily_record中删除     DAILY_RECORD_ID =?

  2. 简而言之,delete-orphan允许父表删除其子表中的少数记录(删除orphan)。

    你应该使用cascade =“delete-orphan”来执行这样的任务。

    Reference