I have a tree-like object, managed by Hibernate. The object has a list of children and each child has its own custom_order within a parent:
<hibernate-mapping>
<class name="MyClass" .../>
<property .../>
<property .../>
<list name="children" cascade="save-update" inverse="false">
<key column="parent_id"/>
<index column="custom_order"/>
<one-to-many class="MyClass"/>
</list>
</hibernate-mapping>
The custom_order exists here in order to maintain the order of children within a parent but has no representation in the Java POJO and is managed directly by Hibernate. The only thing I have to do is to supply a list and custom_order will be auto-generated. So far so good.
What I want to achieve is the ability to use Criteria API and order by custom_order. At the moment I simply can not do anything like
criteria.addOrder(Order.asc("custom_order"));
because there is no such POJO property.
Question: is there a way to use Criteria API for this scenario without adding POJO getter/setter?
EDIT: I don’t mind adding relevant custom_order attribute to MyClass but I just don’t think this is possible in Hibernate.
It is possible to map
custom_orderattribute toMyClasswithout adding getter or setter for this attribute . Just configurecustom_orderattribute to be access by field .Also , to prevent developers from changing the
custom_orderproperty using reflection , makecustom_orderto be read-only by settinginsertandupdatetofalse:Currently ,
Orderin Criteria API only can process mapped properties . If you don’t want to mapcustom_orderattribute toMyClass, you can achieve your purpose ifOrderin Criteria API support sorting by native SQL. There are some requests for this support (HHH-1356 ,HHH-2381 , HHH-3315) but they are still unresolved now.Luckily , someone had already extended the Order class in order to support ordering by native SQL . So ,if you don’t map
custom_ordercolumn forMyClass, you can simply use this extended Order class :