2013-08-24 78 views
2

我有一个一对多关系的两个实体类:查询关联表HQL

@Entity 
@XmlRootElement 
@DynamicInsert (value = true) 
@DynamicUpdate (value = true) 
public class Matchs { 

    @Id @GeneratedValue 
    private Long matchId; 
    private int size; 

    @OneToMany(fetch = FetchType.LAZY) 
    @JoinTable(name = "Match_Users",[email protected](name="match_id"), 
    [email protected](name="user_id")) 
    private List<User> users; 

     //Getters & Setters 
} 

@Entity 
@XmlRootElement 
@DynamicInsert (value = true) 
@DynamicUpdate (value = true) 
public class User { 

    @Id 
    private String username; 
    private String lastName,firstName,password,email; 

    private Date dateOfBirth; 
     //Getters & Setters 
    } 

我想马成顺都为特定的User.This是我的查询:

FROM Matchs WHERE User.username=:username 

这个查询抛出org.hibernate.QueryException。我怎样才能用HQL来实现这一点。

回答

1

您似乎在提取Matchs表中不存在的列上的数据。我没有看到你的Matchs类中的任何列或关系为username

1

FROM Matchs WHERE users.username=:username
在HQL你必须指定关系的名称(用户),而不是针对实体(用户);发生的事情是你必须:

public class Matchs { 

    @Id @GeneratedValue 
    private Long matchId; 
    private int size; 

    @OneToMany(fetch = FetchType.LAZY) 
    @JoinTable(name = "Match_Users",[email protected](name="match_id"), 
    [email protected](name="user_id")) 
    private List<User> users; 

    @OneToMany(fetch = FetchType.LAZY) 
    @JoinTable(name = "Match_winners",[email protected](name="match_id"), 
    [email protected](name="user_id")) 
    private List<User> winners; 

     //Getters & Setters 
} 

如何,在原来的查询,使用实体名称(User),而不是关系名区分winnersusers

1
List<Matchs> list = session.createQuery("from Matchs matchs where matchs.users.username=:username").setParameter("username","myname").list(); 
+0

请提供该代码的功能以及其工作原理的解释。 – hexafraction

+0

我尝试了第二种方法,并得到以下异常:org.hibernate.QueryException:非法尝试使用元素属性引用[username] [FROM com解除引用collection [{synthetic-alias} {non-qualified-property-ref}用户] .kyrogaming.models.Matchs WHERE users.username =:user] – user2054833