mstrom
mstrom

Reputation: 1743

JPA @OrderColumn not ordering the list

I've defined an "Ordinal" INT column in the Child table. For some reason, the automatic ordering is not taking affect. I'm testing this with integration tests that use an in-memory db. Maybe that matters?

public class ParentEntity
    ...
    @OneToMany
    @OrderColumn(name = "Ordinal")
    @JoinColumn(name = "ParentId", nullable = false)
    private List<ChildEntity> childEntities = new ArrayList<>();

public class ChildEntity
    ...
    @ManyToOne
    @JoinColumn(name = "ParentId", nullable=false, insertable=false, updatable=false)
    private ParentEntity parent;

Thanks!

Upvotes: 1

Views: 2166

Answers (1)

V G
V G

Reputation: 19002

The problem is that one of your Entity should be the owner of the bidirectional (ManyToOne) relationship:

public class ParentEntity
    ...
    @OneToMany(mappedBy="parent")//this mappedBy tells that ChildEntity is the owner of the entity
    @OrderColumn(name = "Ordinal")
    @JoinColumn(name = "ParentId", nullable = false)
    private List<ChildEntity> childEntities = new ArrayList<>();

public class ChildEntity
    ...
    @ManyToOne
    @JoinColumn(name = "ParentId", nullable=false, insertable=false, updatable=false)
    private ParentEntity parent;

Excerpt from this page:

In JPA a ManyToOne relationship is always (well almost always) required to define a OneToMany relationship, the ManyToOne always defines the foreign key (JoinColumn) and the OneToMany must use a mappedBy to define its inverse ManyToOne.

Check this page

Upvotes: 2

Related Questions