Hibernate Многие-ко-многим с проблемами загрузки - PullRequest
3 голосов
/ 09 ноября 2011

Мое определение класса выглядит так:

@Entity
@Table(name = "items")
public class Item {
    @Id
    @GeneratedValue
    private long id;

    @Column(unique = true, nullable = false)
    private String url;

    @ManyToMany(fetch = FetchType.EAGER)
    @Fetch(FetchMode.JOIN)
    private Collection<Tag> tags;

    @Column(columnDefinition = "TEXT")
    private String text;
}

и при получении с

 itemSession.createQuery("from Item i where i.url=?").setString(0, url)

требуется два SQL-запроса:

select item0_.id as id1_,
       item0_.text as text1_, 
       item0_.url as url1_ 
   from items item0_ 
   where item0_.url=?

select tags0_.items_id as items1_1_1_, 
       tags0_.tags_id as tags2_1_,
       tag1_.id as id0_0_, tag1_.lastCrawlTime as lastCraw2_0_0_, 
       tag1_.name as name0_0_ 
  from items_tags tags0_ inner join tags tag1_ on tags0_.tags_id=tag1_.id 
  where tags0_.items_id=?

Как я могу сделать это в один?

1 Ответ

2 голосов
/ 10 ноября 2011

HQL игнорирует стратегию выборки, указанную в отображениях. Вы должны форсировать соединение, используя

"from Item i join fetch i.tags where i.url=?"
...