2013-08-24 81 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