Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HQL同一类中的多对多查询_Java_Many To Many_Hql - Fatal编程技术网

Java HQL同一类中的多对多查询

Java HQL同一类中的多对多查询,java,many-to-many,hql,Java,Many To Many,Hql,我有一个包含两个表的数据库,Account和Favorites。收藏夹是一个多对多表。它认为: listowner (foreign key referencing the Account primary key) favorite (also a foreign key referencing the Account primary key) 收藏夹在我的程序中没有自己的类。我只有Account.java,它包含两个集合 private Set<Account> favorite

我有一个包含两个表的数据库,Account和Favorites。收藏夹是一个多对多表。它认为:

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
我目前的尝试:

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

我做错了什么?我没有得到任何例外。

您的查询是错误的
a.listOwner
的类型为
Set
。而且
集合
没有任何
accountName
属性。为了能够对
a.listOwner
的元素添加限制,您需要一个显式联接:

select a from Account a 
inner join a.listOwner owner
where owner.accountName = :name
也就是说,您的整个方法应该简单地替换为

return account.getFavorites();

你的问题是错误的
a.listOwner
的类型为
Set
。而且
集合
没有任何
accountName
属性。为了能够对
a.listOwner
的元素添加限制,您需要一个显式联接:

select a from Account a 
inner join a.listOwner owner
where owner.accountName = :name
也就是说,您的整个方法应该简单地替换为

return account.getFavorites();

如果它没有抛出任何异常,你怎么说它失败了?!它没有抛出任何异常,因为OP捕获所有可能的异常,而不是简单地让它们传播。如果它没有抛出任何异常,你怎么说它失败了?!它不会抛出任何异常,因为OP捕获所有可能的异常,而不是简单地让它们传播。第一个有效,但第二个更好。有时候我想得太多了。非常感谢!第一个有效,但你的第二个更好。有时候我想得太多了。非常感谢!
return account.getFavorites();