To start I have two entities.
User.java
@Entity
public class User {
@Id
private String username;
private String password;
@OneToMany(mappedBy = "to", cascade=CascadeType.PERSIST, orphanRemoval=true)
private ArrayList<Message> messages;
}
public void deleteMessage(Message message){
System.out.println(messages);
messages.remove(message);
System.out.println(messages);
}
Message.java
@Entity
public class Message {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private String id;
@ManyToOne
@NoGson
private User to;
}
The ArrayList messages contains messages for that user and every message in that list has as the “to” field that user. All this is persisted correctly. When I however run the deleteMessage method the first sysout gives the full list correctly and the seconds sysout just gives null instead of the list without the deleted message.
I don’t know if it has something to do with jpa or if I’m just making a stupid mistake but I can’t find the reason why the remove method just removes the entire ArrayList. When I call the deleteMessage function I also call the remove method of the entity manager to delete the message from the database.
Update
After more testing I noticed that the second sysout does give the correct output. So the problem isn’t the remove method from the ArrayList. But the arraylist becomes null after executing the following method.
public void deleteMessage(Message message) {
em.remove(message);
}
So now I know it is a JPA problem.
I solved the problem by resetting the to field of the message that has to be deleted to null. This way the bidirectional connection is broken. If I run the deleteMessage method from above again the ArrayList doesn’t change to null and everything works fine.