2013-10-27 3 views
1

두 개의 테이블, 계정 및 즐겨 찾기가있는 데이터베이스가 있습니다. 즐겨 찾기는 다 대다 테이블입니다. 보유 :HQL 동일한 클래스의 many to many 쿼리

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(); 

에 실패이야? 나는 예외가 없다.

+0

로 대체해야합니다 a.listOwner의 요소에 제한을 추가 할 수 있습니다, 당신은 명시 적으로 가입해야합니다 그게 그 실패라고하니? – SudoRahul

+0

OP는 단순히 예외를 전파시키는 대신 모든 가능한 예외를 catch하기 때문에 어떤 예외도 발생시키지 않습니다. –

답변

1

검색어가 잘못되었습니다. a.listOwnerSet<Account>입니다. Set<Account>에는 accountName 속성이 없습니다. 그 어떤 예외를 던지는하지 않으면

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

, 전체 방법은 간단하게, 어떻게

return account.getFavorites(); 
+0

첫 번째 작품은 두 번째 작품보다 좋습니다. 때때로 나는 물건을 생각할 때가있다. 무리 감사! – ohyeah