Create an index on a column in a one-to-many relationship
I have a one-to-many relationship between two classes:
class Parent {
List<Child> children;
}
class Child {
String name;
}
I am using a file .hbm.xml
to define my mapping from Java classes to tables. Something like that:
<class name="Parent" table="parent">
<list name="children">
<key column="parent_id" />
<list-index column="idx" />
<one-to-many class="Child" />
</list>
</class>
<class name="Child" table="child">
<property name="name" type="string" />
</class>
This works great.
Now I want to create a column index (not a list index) on the column Child.parent_id
. It looks like the tag <one-to-many>
doesn't allow nested tags <column>
, so I tried adding a bi-directional association to the mapping Child
like this:
<many-to-one name="parent" insert="false" update="false">
<column name="parent_id" index="true">
</many-to-one>
But I am getting an exception:
org.hibernate.PropertyNotFoundException: Could not find a getter for parent in class Child
So how can I create an index on a column Child.parent_id
without adding a field parent
to the class Child
? I am using Hibernate 3.5.6 and PostgreSQL 9.3.
source to share
At first I didn't understand what you are looking for, but I think I do.
You have defined list-index
which is used to store the java.util.List index, not the Child's parent_id. So you are looking at how to create a real database index. This can be easily done with an annotation like this:
@OneToMany(cascade = { CascadeType.ALL })
@JoinColumn(name="parent_id")
@Index(name = "idx_parent_id", columnNames = "parent_id")
private List<Child> images = new ArrayList<Child>();
And in xml config it will look like,
<list name="children">
<key>
<column index="parent_id_idx" name="parent_id"/>
</key>
<list-index column="idx"/>
<one-to-many class="hr.winkme.server.model.entities.Child"/>
</list>
Hope this helps.
source to share