tags:

views:

122

answers:

1

I am creating a record of Widgets with Hibernate. It's pretty basic. I've got an hbm.xml file describing the object, a DAO class that creates and saves them, etc.

However, there is an explicit sorting order to the widgets, and each new Widget needs to be inserted with a sortIndex column value that is greater than all other sortIndex column values (i.e. new widgets are automatically sorted last). I can't for the life of me figure out how to accomplish this.

Hibernate is perfectly capable of setting ID columns automatically, and it makes sense to me that it would be able to set some other column to a unique value according to a formula like max(sortIndex)+1 or according to some increasing sequence generator value, but I can't find a reference in the documentation to this sort of thing. Could someone point me in the right direction?

One approach that sprang to mind was to just query for the highest sortIndex manually, but I started worrying about two different transactions both finding the same new sortIndex.

+1  A: 

I hate to say it, but I think you're best off just doing this programmatically. Just something in the lines of:

public void saveNewWidget(Widget widget) {
    Session session = ...;
    int sortIndex = ((Integer) session.createQuery("select max(w.sortIndex) from Widget w").uniqueResult()) + 1;
    widget.setSortIndex(sortIndex);
    session.save(widget);
}

(Note: Not thread-safe. I can't see a good way to make it safe except by locking the entire table. I shall blame tiredness.)

The reason for this is that it seems neither UserType nor a custom Interceptor can help you here. So, if you really want to do this yourself you might have to write your own ClassPersister. And that is the path to madness.

waxwing