在级联EntityManager上删除

时间:2012-12-09 14:54:55

标签: jpa cascade entitymanager cascading-deletes

情况如下: 我有2个实体交易者和客户: - 一个客户与一个交易者相关联 - 一个交易者可以与一个或多个客户关联 在使用EntityManager.remove(t)删除交易者然后提交时,将自动删除与该交易者相关的所有客户。这很好,因为它是级联删除。 问题:

1 - 我如何删除我的交易者并将其客户重新影响到另一个?

2 - 解决方案是否在于在mySQL中设置级联效果,或者它驻留在entityManager和MySQL中? 非常感谢您的帮助。

客户实体

public class Client implements Serializable {
    @Transient
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id_client")
    private Integer idClient;
    @Column(name = "id_portefeuille")
    private Integer idPortefeuille;
    @Column(name = "id_entreprise")
    private Integer idEntreprise;
    @Column(name = "id_trader")
    private Integer idTrader;
    //other attributes 
    @JoinColumn(name = "id_trader", referencedColumnName = "id_trader", updatable = false, insertable = false)
    @ManyToOne
    private Trader idTrader2;
    //getters and setters 

交易者实体

public class Trader implements Serializable {
        @Transient
        private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this);
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = "id_trader")
        private Integer idTrader;
        @Column(name = "nom")
        //other attributes
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "idTrader2")
        private Collection<Client> clientCollection;
        //getters and setters 

主要代码

//Getting The trader selected in a JTable        
 Trader t = traderList.get(tableTrader.getSelectedRow());

 for (Iterator<Client> it = t.getClientCollection().iterator(); it.hasNext(); ) {

           //Getting the Clients releated to this trader
            Client c = it.next();

           //Affecting the client to an other trader 
           // i chose an existing one randomly 
            c.setIdTrader2(traderList.get(2));
           traderList.get(2).getClientCollection().add(c);

           it.remove();
    }
            entityManager.flush();
            entityManager.remove(t);
        }

1 个答案:

答案 0 :(得分:0)

在级联配置中不应该删除,在MySQL中也不应该在实体映射中。因此,该方法看起来像这样(假设存在双向关联,并且getClients()直接返回持久列表,而不制作防御性副本或将其包装到未修改的代理中):

public void deletedTrader(Trader toDelete, Trader newAssignedTrader) {
    for (Iterator<Client> it = toDelete.getClients().iterator(); it.hasNext(); ) {
        Client c = it.next();
        c.setTrader(newAssignedTrader);
        newAssignedTrader.getClients().add(c);
        it.remove();
    }
    em.remove(toDelete);
}