tobier tobier - 4 months ago 22
Java Question

JPA (EclipseLink) list order

I'm having some problem with keeping the order of a list during persistence when using EclipseLink. Am I missing some setting in EclipseLink, or forgetting to use some annotation?

I have two classes that looks somewhat like this:

@Entity
@Table(name = "sequence")
public final class Sequence {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "sequence")
private List<Run> runs;

// Other fields
// ...
}

@Entity
@Table(name = "run")
public final class Run {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@ManyToOne
@JoinColumn(name = "seq_id", nullable = false)
private Sequence sequence;

@Column(nullable = false)
private String comment;

// Other fields
// ...
}


Now, I expect that when I add instances of the latter class to the former, the order in the list will be kept when persiting:

Run a = new Run();
a.setComment("a");

Run b = new Run();
b.setComment("b");

List<Run> runs = new LinkedList<Run>();
runs.add(a);
runs.add(b);

Sequence seq = new Sequence();
seq.setRuns(runs);

persist(seq); // order in database should be "a", then "b"


However, when I check the database, it's not always so that the instance a gets a lower identifier than b; it seems to behave as if the list is just a bucket.

How do I keep the order of the list when using persistence? If the instance a is added before b, I want to keep the order in the database as the entries are results of a sequential execution of tests and the order must be perserved.

Thanks for your help!

Answer

If you want to keep the order, you'll need an @OrderColumn annotation - by default, collection are saved with a "bag" semantic (no order involved). This can be added on a OneToMany or ManyToOne annotations.

Something like:

@OneToMany(cascade = CascadeType.PERSIST, mappedBy = "sequence")
@OrderColumn
private List<Run> runs;

See http://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html for the info.