These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: Querying on many-to-many relationship using bags
PostPosted: Mon Jul 07, 2008 3:50 am 
Newbie

Joined: Mon Jul 07, 2008 3:16 am
Posts: 1
I'm building a simple movie database with NH to learn how it all works, and have a typical many-to-many relationship between movies & genres. I want to create a feature to browse movies by genre, and while I can get this working, it feels a bit off.

You'll notice that it's pulling rows from both the genre table & the mapping table, which seems unecessary (though by no means horrible). Is there a more efficient means for querying based on a many-to-many relationship? Or is this as good as it gets?

I'm using 2.0.0Beta1 with SQL Server 2005 and .NET 3.5.

Mappings:
Code:
<class name="Movie">
  <id name="Id">
    <generator class="identity" />
  </id>
  <property name="Title" type="String" length="255" />
  <bag name="Genres">
    <key column="MovieId" />
    <many-to-many class="Genre" column="GenreId" />
  </bag>
</class>

<class name="Genre">
  <id name="Id">
    <generator class="identity" />
  </id>
  <property name="Title" type="String" />
</class>


Classes:
Code:
public class Movie
{
   public virtual int Id { get; set; }
   public virtual string Title { get; set; }
   public virtual IList<Genre> Genres { get; set; }
}

public class Genre
{
   public virtual int Id { get; set; }
   public virtual string Title { get; set; }
}


Code:
Code:
_session.CreateCriteria(typeof(Movie))
.CreateCriteria("Genres")
    .Add(Expression.Eq("Id", genre.Id));


This generates the following query:
Code:
SELECT this_.Id as Id0_1_, this_.Title as Title0_1_,
genres3_.MovieId as MovieId, genre1_.Id as GenreId, genre1_.Id as Id2_0_,
genre1_.Title as Title2_0_, this_.Title as __hibernate_sort_expr_1__
FROM Movie this_ inner join MoviesToGenres genres3_ on this_.Id=genres3_.MovieId
inner join Genre genre1_ on genres3_.GenreId=genre1_.Id WHERE genre1_.Id = @p0


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.