1

I have a database with two tables, Account and Favorites. Favorites is a many-to-many table. It holds:

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

Favorites does not have its own class in my program. I only have Account.java, which holds two sets.

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

The relevant mapping file:

<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>

Now, saving to the database works fine. I can save a favorite account with a listowner and see him appear when directly accessing the database. But I can't get this information out of the database again. I want a list of all favorites of an account. In SQL, this would be:

SELECT favorite 
FROM favorites 
WHERE listowner = "Bob"

My current attempt:

 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;
    }
}

According to the debugger, it's failing on

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

What am I doing wrong? I'm not getting any exceptions.

4

1 回答 1

1

你的查询是错误的。a.listOwner是类型Set<Account>。并且 aSet<Account>没有任何accountName属性。为了能够对 的元素添加限制a.listOwner,您需要显式连接:

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

也就是说,您的整个方法应该简单地替换为

return account.getFavorites();
于 2013-10-27T11:47:54.363 回答