0

情况如下:我有 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);
        }
4

1 回答 1

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);
}
于 2012-12-09T15:03:34.157 回答