In the database, you might model player table to have a foreign key reference to the team table.
Now you have to decide if there can exist a player that does'nt belong to any team. If that is the case the foreign key is obviously nullable. You dont necessarily need to have a team in place to create a player.
So code#1 will work. I mean if you have a team, then you can set it on the player bean (as you have in this case). You can choose to ignore that as well.
But if your business demands that a player be associated with a team when he is inducted, then you would probably model the reference to the team as a NON-nullable foreign key in the Player table.
In that case, code#1 will result in a NUll Foreign key violation at the line where you do a
playerHome.create()
So code#1 will not work.
In that situation, code#2 makes sense.
when calling p.setTeam(t); method, what this is mean to the container ?
what the container do under the cover when calling this method ?
The container needs to make sure that relationships are persisted ok , meaning the foreign key constraints are met. So it will make sure that the team foreign key is also inserted while creating the Player. It also will make sure that the Player is not persisted just at the end of ejbCreate but instead after ejbPostCreate.
Infact there is no mandate as to when the actual insert to the database s'd happen. App servers might do a batch insert/update to the database at the end of transaction to take advantage of the
JDBC batch update feature of the driver.
Either way the container will make sure that the database integrity is maintained.