I have a problem with fetching many-to-many relation in my hibernate+spring app:
so it looks like this - there are 3 tables:
user have id (PK);
copy have id (PK);
orderz have user_id and copy_id (together a PK) which links between the first 2 tables.
more details:
Code:
TABLE `user` (
`id` int(10) AUTO_INCREMENT,
`user_level_id` int(10),
`login` varchar(16),
`pass` varchar(32),
`first_name` varchar(32),
`last_name` varchar(32),
`email` varchar(32),
`pesel` varchar(13),
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=5 ;
Code:
TABLE `copy` (
`id` int(10) AUTO_INCREMENT,
`book_id` int(10),
`state_id` int(10),
`level_id` int(10),
`date` datetime,
PRIMARY KEY (`id`),
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci AUTO_INCREMENT=13 ;
and a many-to-many link between them:
Code:
TABLE `orderz` (
`user_id` int(10),
`copy_id` int(10),
PRIMARY KEY (`user_id`,`copy_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_polish_ci;
I've made mapping for the first 2 (I'll omit less important things):
User.hbm.xml:Code:
<hibernate-mapping>
<class name="orm.User" table="user">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="identity"/>
</id>
...........
<set name="orders" table="orderz" fetch="join" lazy="true">
<key column="user_id"/>
<many-to-many class="orm.Copy" column="copy_id"/>
</set>
</class>
</hibernate-mapping>
Copy.hbm.xml:Code:
<hibernate-mapping>
<class name="orm.Copy" table="copy">
<id name="id" type="java.lang.Integer">
<column name="id"/>
<generator class="identity"/>
</id>
..........
<set inverse="true" name="orders" table="orderz" fetch="join" lazy="true">
<key column="copy_id"/>
<many-to-many class="orm.User" column="user_id"/>
</set>
</class>
</hibernate-mapping>
and now I want to get user with all his copies.
HQL for this:
from User u
left outer join u.orders o
where u.id = :user_idI know I could make it easier but I'll have to add some criteria for those copies so not all copies will be returned.
Now - what's the problem?the problem is Hibernate returns a List of collections which 1st element is User object, and the second is Copy object. The size of that List = number of Copies in the DB which are connected with that user.
I would like to receive User object with an orders collection where are Copy objects (only those which I want).
I think it should be like this and I'm doing sth wrong. Can you help me?