问题描述
我有3张桌子:
-
customer(idCustomer,...)
-
is_managed(idCustomer,idPerson)
-
sales_person(idPerson,...)
customer(idCustomer,...)
is_managed(idCustomer,idPerson)
sales_person(idPerson,...)
customer
和sales_person
之间存在@ManyToMany
关系.
当我执行删除操作时,它可以正常工作:删除customer
,is_managed
和sales_person
.
When I perform a delete, then it works fine: the customer
, is_managed
and sales_person
are deleted.
但是,当我执行更新时,会更新customer
和is_managed
,但不会更新sales_person
.
But when I perform an update, then the customer
and is_managed
are updated, but the sales_person
not.
例如,如果我通过删除sales_person
来更新customer
,则会在is_managed
表中将其删除,但不会在sales_person
表中将其删除.
For example, if I update a customer
by deleting the sales_person
, it's deleted in is_managed
table, but not in sales_person
table.
这是怎么引起的,我该如何解决?
How is this caused and how can I solve it?
以下是相关代码:
// update customer
public String updateCustomer(Customer customer,ArrayList<Sales_person> sales_persons,ArrayList<Involved_group_relation> involved_groups, Macro_market macro_market)throws IOException {
// insert the sales_person attached to the customer
ArrayList<Sales_person> sales_personC = new ArrayList<Sales_person>();
sales_personC.addAll(sales_persons);
customer.setSalesPersons_BelongTo(sales_personC); // insert in customer the sales_persons
em.merge(customer);
return customer.getNameCustomer();
}
// entity customer
@Entity
@Table(name="customer")
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
private Long idCustomer;
private String titleTypeAccount;
private String nameCustomer;
/** RELATIONS **/
// CUSTOMER - SALES_PERSON
@ManyToMany(
cascade={CascadeType.ALL}
)
@JoinTable(
name="is_managed",
joinColumns=@JoinColumn(name="idCustomer"),
inverseJoinColumns=@JoinColumn(name="idPerson")
)
private Collection<Sales_person> salesPersons_BelongTo;
...
...
// entity sales_person
@Entity
@Table(name="sales_person")
public class Sales_person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long idPerson;
private String nameSalesPerson;
private String jobFunction;
private String titleOrganization;
@ManyToMany(
mappedBy="salesPersons_BelongTo"
)
private Collection<Customer> customers;
...
...
推荐答案
如果要从数据库中删除SalesPerson,则必须在SalesPerson上调用em.remove().仅仅调用merge()还不够.
If you want the SalesPerson to be deleted from the database, then you must call em.remove() on the SalesPerson. Calling merge() is not enough.
此外,如果您希望合并SalesPerson的更改,则还必须在SalesPerson上调用merge(),或在salesPersons_BelongTo关系上设置级联合并.
Also, if you want the SalesPerson's changes to be merged, you must call merge() on the SalesPerson as well, or set cascade merge on the salesPersons_BelongTo relationship.
还要确保您保持双向关系的双方,而不仅仅是一侧.
Also ensure you are maintaining both sides of the bi-directional relationship, not just one side.
这篇关于JPA更新在多对多关系中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!