/**
* Test the detach method: make an object persistent, and detach it out of an active transaction.
*/
public void testDetachCopy() {
logger.log(BasicLevel.DEBUG, "***************testDetachCopy*****************");
Team t = new Team("Bordeaux",null,null);
Collection players = new ArrayList();
Player p1 = new Player("p1", t, 25);
players.add(p1);
Player p2 = new Player("p2", t, 32);
players.add(p2);
t.setPlayers(players);
Coach c = new Coach("c1", 5, t);
t.setCoach(c);
PersistenceManager pm = pmf.getPersistenceManager();
pm.currentTransaction().begin();
logger.log(BasicLevel.DEBUG, "make persistent the team " + t.toString());
pm.makePersistent(t);
pm.currentTransaction().commit();
t = null;
p1 = null;
p2 = null;
c = null;
pm.evictAll();
pm.close();
pm = pmf.getPersistenceManager();
Query query = pm.newQuery(Team.class, "players.contains(player) & player.age<12");
query.declareVariables("Player player");
Collection results = (Collection)query.execute();
assertTrue("The result of the query should be empty.", results.isEmpty());
query.closeAll();
query = pm.newQuery(Team.class, "players.contains(player) & player.age>12");
query.declareVariables("Player player");
results = (Collection)query.execute();
assertTrue("The result of the query shouldn't be empty.", !results.isEmpty());
Team res = (Team) results.iterator().next();
Collection cpl = res.getPlayers();
Iterator itPlayer = cpl.iterator();
while(itPlayer.hasNext()) {
Player pl = (Player) itPlayer.next();
assertTrue("The age of the player should be over 12. It is " + pl.getAge() + ".", pl.getAge()>12);
}
query.closeAll();
query = pm.newQuery(Team.class, "town==\"Bordeaux\"");
results = (Collection)query.execute();
assertEquals("The result of the query shouldn't be empty.", false, results.isEmpty());
Team toDetach = (Team) results.iterator().next();
query.closeAll();
//detach the team t
Team copyOfT = (Team) pm.detachCopy(toDetach);
try {
assertNotNull(copyOfT);
assertEquals("Town of team and detached team are not the same", toDetach.getTown(), copyOfT.getTown());
assertEquals("Coach experience of team and detached team are not the same",toDetach.getCoach().getExperience(), copyOfT.getCoach().getExperience());
assertEquals("Coach name of team and detached team are not the same",toDetach.getCoach().getName(), copyOfT.getCoach().getName());
//print the team out
logger.log(BasicLevel.DEBUG, copyOfT.toString());
} catch (Exception e) {
fail(e.getMessage());
} finally {
if (pm.currentTransaction().isActive())
pm.currentTransaction().rollback();