Hibernate - 双左连接

时间:2011-04-18 16:20:27

标签: hibernate hql left-join

我有以下3个班级,其中的关系是联赛1- *队1- *球员 联赛和球队由league_team表链接

class League {

@NamedQueries( { @NamedQuery(name = "League.findJasperLeagueDetail", query = "from League r "
        + "where league_id = :Id") })
//getter setter methods
...

private Set<Team> team;

@OneToMany(cascade = CascadeType.ALL)
@JoinTable(name="league_team",joinColumns=@JoinColumn(name="team_id"),
inverseJoinColumns=@JoinColumn(name="league_id"))

public Set<Team> getTeams() {
    return team;
    }
}


class Team {
private Set<Player> players;

@OneToMany(mappedBy="teams")
public Set<Player> getPlayers(){
        return this.players;
    }
}

class Player{

private Team team;

@ManyToOne
@JoinColumn(name="team_id") 
public Team getTeam(){
        return this.team;
}
}   


public static void main (String[] ag){

// Get the entity manager em

        League league = em.find(League.class, 52L);
    Query query = em.createNamedQuery("League.findJasperLeagueDetail");
    query.setParameter("leagueId", league.getId());


    List<League> result = query.getResultList();
        Set teams = result.get(0).getReports();
        Iterator<Team> it = teams.iterator();
        if(it.hasNext()){
            Set<Player> players = it.next().getPlayers();

- &GT;在这里我得到以下异常:

java.util.NoSuchElementException
    at java.util.HashMap$HashIterator.nextEntry(Unknown Source)
    at java.util.HashMap$KeyIterator.next(Unknown Source)
    at org.hibernate.collection.AbstractPersistentCollection$IteratorProxy.next(AbstractPersistentCollection.java:577)

如何通过一组球队获得联盟对象,其中每支球队都有一组球员?基本上,我如何获得双左连接?

1 个答案:

答案 0 :(得分:0)

看起来你正在设置错误的参数。

Query query = em.createNamedQuery("League.findJasperLeagueDetail");
//query.setParameter("leagueId", league.getId()); <--no named parameter 'leagueId'
query.setParameter("Id", league.getId());

喝彩!