i have an application with a derby database and use eclipselink as the persistence api.
Say i have a gui with a list of teams. Each team has a number of players on it. The relationship in the team class looks like this:
@OneToMany(mappedBy = "team", fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
private List<player> players = new ArrayList<player>():
and the player class like this:
@ManyToOne(targetEntity = Team.class)
@JoinColumn(name = "teamID", nullable = false, referencedColumnName = "ID")
private Team team;
So i now start my application and it fills a list with all existing teams:
public List<Team> getTeams()
{
TypedQuery<Team> query = em.createQuery("SELECT t FROM Team t", Team.class);
List<Team> teams = query.getResultList();
return teams;
}
All is working right so far, only the teams are loaded, not the players. Say i now open a table with the players of a team by selecting a team and exectue the command for this. The table is filled with:
team.getPlayers();
So now all the players of this team are loaded, cause they are now needed.
But after i close the table they remain loaded, but i would like to “unload” them again so that they don’t remain in memory – how would i do this?
If you want to get rid of managed entities from its context you can call
EntityManager.clear()method (callingEntityManager.flush()before). This operation, however, removes all managed entities, which is not necessarily what you want, since this might cause additional database hits.If you are lucky and you can use JPA 2.0 there is a better option:
EntityManager.detach(Object)method, which is removing given object from persistence context.