Java HQL同一类中的多对多查询
我有一个包含两个表的数据库,Account和Favorites。收藏夹是一个多对多表。它认为: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
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();