簡體   English   中英

HQL在同一個類中進行多對多查詢

[英]HQL many to many query in the same class

我有一個包含兩個表的數據庫,即“帳戶”和“收藏夾”。 收藏夾是一個多對多表。 它擁有:

listowner (foreign key referencing the Account primary key)
favorite (also a foreign key referencing the Account primary key)

我的收藏夾在我的程序中沒有它自己的類。 我只有Account.java,它擁有兩個集合。

private Set<Account> favorites;
private Set<Account> listOwner;
//the getters and setters for these sets

相關的映射文件:

<set name="favorites" table="favorites" inverse="true" cascade="all">
        <key column="listowner" />
        <many-to-many column="favorite"  class="Models.Account" />
 </set>

<set name="listOwner" table="favorites" cascade="all">
        <key column="favorite" />
        <many-to-many column="listowner" class="Models.Account" />
</set>

現在,保存到數據庫可以正常工作。 我可以用列表所有者保存一個喜歡的帳戶,並在直接訪問數據庫時看到他出現。 但是我無法再次從數據庫中獲取此信息。 我想要一個帳戶的所有收藏夾的列表。 在SQL中,這將是:

SELECT favorite 
FROM favorites 
WHERE listowner = "Bob"

我目前的嘗試:

 public static List<Account> getFavorites(Account account)
{
    List<Account> list = null;
    Transaction tx = null;

    try
    {
        tx = session.beginTransaction();
        list = session.createQuery("from Account a where a.listOwner.accountName = :name").setParameter("name", account.getAccountName()).list();
        tx.commit();
    } catch (Exception e)
    {
        if (tx != null)
        {
            tx.rollback();
        }
        System.out.println("getFavorites failed");
        e.printStackTrace();
    } finally
    {
        return list;
    }
}

根據調試器,它正在失敗

 list = session.createQuery("from Account a where a.listOwner.accountName = :name").setParameter("name", account.getAccountName()).list();

我究竟做錯了什么? 我沒有任何例外。

您的查詢是錯誤的。 a.listOwner的類型為Set<Account> 並且Set<Account>沒有任何accountName屬性。 為了能夠對a.listOwner的元素添加限制,您需要一個顯式a.listOwner

select a from Account a 
inner join a.listOwner owner
where owner.accountName = :name

也就是說,您的整個方法應該簡單地替換為

return account.getFavorites();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM