Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want that the players are removed as delete-orphan, you need that the players loose the reference to the team and the save the team.</p> <p>What you are doing is the following:</p> <ul> <li>Create a new object team.</li> <li>Feed the team with 3 players</li> <li>Persist</li> </ul> <p>After that, each player row will contain a FK to team (id=1).</p> <p>Then the code creates a new team, with the same id, and feed 2 players and persist.</p> <p>At that point there still will be a player in DB that references to team 1.</p> <p>From my POV every different business object should have their own business key. If you want to overwrite the players of team 1, you should first retrieve team where id = 1, and then feed the players.</p> <pre><code>private Team createTeam(int players) { Team team = session.get(Team.class, 1); if (team == null) { team = new Team(); team.setName("Bears"); team.setId(1); } team.clearPlayers(); for(int i=1 ; i&lt;=players; ++ i){ Player player = new Player(); player.setId(i); player.setName("Player"+i); team.addPlayer(player); } return team; } // Team.java private void clearPlayers() { players.clear(); } </code></pre> <p>BTW, another advice. Don't allow to modify your players directly, that can lead to HibernateErrors such us <em>"Don't change the reference to a collection..."</em>. Instead of setPlayers(), add methods for <code>addPlayer()</code> and <code>removePlayer()</code></p> <pre><code>private void adddPlayer(Player player) { player.setTeam(this); players.add(player); } private void removePlayer(Player player) { player.setTeam(null); players.remove(player); } </code></pre> <p>Also, a collection is mutable, so make getPlayers() to return a non-modifiable collection:</p> <pre><code>private Set&lt;Player&gt; getPlayers() { return Collections.unmodifiableSet(players); } </code></pre> <p>Hope this sheds some light :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload