Gotcha: preserving the ordering in collections when using JPA

This week I was faced with the requirement to store the ordering of a collection from a Java web application to a database. In plain Java, retaining the ordering within a collection is a no-brainer: you just use one of the java.util.List implementations. And saving the order into a database table should be as easy as a couple of INSERT statements in the correct order, right? Well, if you’re using JPA for ORM then it really isn’t that straightforward. As it turns out JPA does not take the ordering of a List into consideration, which imho is a serious design flaw. Forunately, as of version 2.0 a workaround was added to the spec: you can annotate relationships with @OrderColumn.