问题
I have 3 tables:
customer(idCustomer,...)
is_managed(idCustomer,idPerson)
sales_person(idPerson,...)
There is a @ManyToMany
relation between customer
and sales_person
.
When I perform a delete, then it works fine: the customer
, is_managed
and sales_person
are deleted.
But when I perform an update, then the customer
and is_managed
are updated, but the sales_person
not.
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?
Here's the relevant code:
// 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;
...
...
回答1:
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.
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.
来源:https://stackoverflow.com/questions/15835741/jpa-update-doesnt-work-in-a-many-to-many-relationship