Consider the following simple example: There are many players in one team, and a player can belong to only one team.
@Entity public class Team { @OneToMany(cascade = CascadeType.ALL, mappedBy = "team") @Cascade({ org.hibernate.annotations.CascadeType.ALL, org.hibernate.annotations.CascadeType.DELETE_ORPHAN}) private Set<Player> player = new HashSet<Player>(); } @Entity public class Player { @NotNull @ManyToOne(targetEntity = Team.class) @JoinColumn(name = "team_id") private Team team; }
What I want to achieve is moving all the players from team A to team B and then removing team A. I loop the players from team A and set their team to team B (here: "this"):
Iterator<Player> iterator = teamA.getPlayer().iterator(); while(iterator.hasNext()){ Player player = iterator.next(); player.setTeam(this); player.merge(); } teamA.remove();
After that, a flash (autoflush) is executed, but I also tried to execute a flash before the A.remove () command. This code works without errors, but then the players from team A are deleted from my data source due to the cascade configuration, since teamA.remove () removes all players from team A.
I wonder why they are still associated with team A, because I also tried (and checked in the debugger) to remove all players from Set, so when A..remove () is called, the set is empty. The exceptions that were thrown in these cases either stated that "the deleted entity transferred for storage" or "the deleted entity transferred for storage". Of course, this works if I create a new transition player, copy all the properties and .persist ().
How to do this by simply “pulling” the relationship?
source share