@OrderBy on a mappedBy (inverse) List is applied in reverse direction

#1

Hi,

with ObjectDB 2.9.6_01 (objectdb-jk) on JDK 25 / Windows, @OrderBy on an inverse @OneToMany(mappedBy=...) list loads the elements in the opposite direction of the one specified.

Test case

@Entity
public class U {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;

    public String name;

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @OrderBy("code ASC")
    public List<C> cards = new ArrayList<>();
}

@Entity
public class C {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    public long id;

    public String code;

    @ManyToOne(fetch = FetchType.EAGER)
    public U user;
}

public class Main {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory(args[0]); // new empty .odb file

        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();
        U u = new U();
        u.name = "test";
        em.persist(u);
        for (String code : new String[] { "3", "1", "5", "2", "4" }) {
            C c = new C();
            c.code = code;
            c.user = u;
            em.persist(c);
        }
        em.getTransaction().commit();
        em.close();

        em = emf.createEntityManager();
        for (U x : em.createQuery("SELECT u FROM U u", U.class).getResultList()) {
            for (C c : x.cards) System.out.print(c.code + " ");
            System.out.println();
        }
        em.close();

        em = emf.createEntityManager();
        for (C c : em.find(U.class, u.id).cards) System.out.print(c.code + " ");
        System.out.println();
        em.close();
        emf.close();
    }
}

Results

Same order with the query and with find, each run on a new database file:

@OrderBy Loaded order
"code" 5 4 3 2 1
"code ASC" 5 4 3 2 1
"code DESC" 1 2 3 4 5
"code ASC, id ASC" 5 4 3 2 1
"id ASC" 4 2 5 1 3 (descending id, reverse of insertion)

The result is the same when running with -javaagent:objectdb-jk-2.9.6_01.jar.

According to the manual (JPA Entity Fields, inverse fields), @OrderBy("name") should populate the list as SELECT e FROM Employee e WHERE e.department = :d ORDER BY e.name, so ascending order is expected.

Related question

As a workaround I tried to sort the list in a @PostLoad callback with cards.sort(Comparator.comparing(c -> c.code)). The list (com.objectdb.o.ILP) already holds the 5 elements at that point, but sort() has no effect and no exception is thrown. Is an inverse list meant to be read-only in memory?

For now we use @OrderBy("code DESC") to get ascending order, but that would break once this is fixed. Could you confirm whether this is a bug?

Thanks

Reply