简体   繁体   中英

Java JPA flush() doesn't update database in one to many relationship?

So I have a Person class which has one to many relationship to Address class ( not really in my code but its similar like this, just to make it easier ).

I'm trying to set null to addresses then flush it then re insert with new addresses but it won't work since there is a possibility of duplicate key in Address table even if I set addresses to null then flush it.

I need to remove every address first then set them to null then flush.

-------------------------------------------------------------
// 1, this won't work, duplicate key exception when committing in Address table if there is a same address in newAddress with address in this person addresses

em.getTransaction().begin();
person.setAddresses(null);
em.flush();

// print the address, count is still the same with before depends on how many address this person has

String query = "SELECT P.addresses FROM Person P WHERE P = :pr"; 
ObservableList<Address> addresses= FXCollections.observableArrayList(
                                          em.createQuery(query, Address.class)
                                            .setParameter("pr", person)
                                            .getResultList());
System.out.println("COUNT: " + addresses.size() +  " name: " +  addresses.get(0).getName());  

person.setAddresses(newAddresses);
em.commit();             // exception

-----------------------------------------------------------------------

// 2, this works

em.getTransaction().begin();
for(Address a : person.getAddresses() {
em.remove(a);
}
person.setAddresses(null);
em.flush();

// print the address, count is still one and its null

String query = "SELECT P.addresses FROM Person P WHERE P = :pr"; 
ObservableList<Address> addresses= FXCollections.observableArrayList(
                                          em.createQuery(query, Address.class)
                                            .setParameter("pr", person)
                                            .getResultList());
System.out.println("COUNT: " + addresses.size() ); 
em.commit();         // fine

---------------------------------------------------------------------

One to many relationships are controlled by the the owner side, which is address in your case. Therefore you must set/remove the relationship from the address.

Person.setAddresses won't have any effect for JPA, the proper way is iterating through the addresses and setting address.person = null or removing the addresses completely. The rest should follow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM