This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
Hi. I have two entity beans, TeamBean and PlayerBean. and the relationship is one to many, nidirectional. TeamBean has a CMR field called players and PlayerBean has a CMR field called team. I have a session bean (session facade bean) and this beanhas a method to create a new player. the code is :
now, in the PlayerBean I has an ejbCreate(String, String) method and a similiar EMPTY ejbPostCreate(String, String) method. I have read a note that said: you must set the CMR field in the ejbPostCreate( ) method like this :
is this note true? if both are true, in which situations I should consider to use each one ? what is the impact of each one ? should I change something in session bean if I used the second approach (like not calling p.setTeam(t); ) ? I have a last question please: when calling p.setTeam(t); method, what this is mean to the container ? what the container do under the cover when calling this method ? any help is appreciated..
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
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.