Hello,
in my application, there are the classes Person and Category with a many-to-many-relation between them. Now I want to select all persons with categoryId = 1.
I have been trying to create this query for hours, but it does not work. Can someone explain me how to write this query?
Here are the relevant parts of my mapping files.
Person.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="false" auto-import="true">
<class name="de.waldhausweg7.model.Person" table="Person">
<id name="personId" type="int">
<generator class="increment" />
</id>
<!-- n:m-Beziehung zu Kategorie -->
<set name="categories" table="person_category" lazy="false">
<key column="personId" />
<many-to-many class="de.waldhausweg7.model.Category" column="categoryId" />
</set>
</class>
</hibernate-mapping>
Category.hbm.xml
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping default-lazy="false" auto-import="true">
<class name="de.waldhausweg7.model.Category" table="Category">
<id name="categoryId" type="int">
<generator class="increment" />
</id>
<property name="categoryName" column="categoryName" />
<property name="comment" column="comment" />
</class>
</hibernate-mapping>
Here some of my attempts:
Code:
String queryString = "select * from person p, person_category pc where p.personId = pc.personId and pc.categoryId = 1";
String queryString = "select * from Person p where p.categories in (select * from Category c where c.categoryId = 1)";
String queryString = "select p from Person as p where :categoryId in elements (p.categories)";
String queryString = "select p from Person as p where :categoryId in elements (p.categories.categoryId)";
String queryString = "select p from Person p join p.categories c where c.categoryId = :categoryId";
Everytime I get null as result although there is a record which fits to the condition.
I would be thankful for every hint.
Christopher