JPA + Hibernate - reconnect objects from @OneToMany relationship

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?

+4
source share
4 answers

You tried:

 team2.setPlayers(team1.getPlayers(); team1.setPlayers(null); for (Player player : team2.getPlayers() { player.setTeam(team2); } 
+1
source

I think you need to clear the set before calling remove on teamA. But you said you tried it?

Is the new team permanent?

0
source

I believe the culprit is DELETE_ORPHAN. From Help Annotations:

DELETE_ORPHAN applies only to @OneToMany associations and indicates that the delete () / remove () operation should be applied to any child that is removed from the association. In other words, if a child is dereferenced by a constant parent and DELETE_ORPHAN is used, the orphaned child will be deleted.

But this is not what you want, since you are “educating” the Player.

0
source

I think that after you change the team of players, you should call flush () and then call refresh () on team A, and then call remove () on team A.

0
source

Source: https://habr.com/ru/post/1301595/


All Articles