我有一個包含兩個表的帳戶和收藏夾的數據庫。收藏夾是一個多對多的表格。它成立於:HQL在同一類中多對多查詢
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();
我在做什麼錯?我沒有得到任何例外。
代替如果其不拋出任何異常,如何你說它的失敗?! – SudoRahul
它不會引發任何異常,因爲OP會捕獲所有可能的異常,而不是簡單地讓它們傳播。 –