1

Given a Parent class which has many Children, can Hibernate automatically manage the order of said children? From reading documentation and searching, it seems that the @OrderColumn annotation may enable this, but I've not found any examples of how to do it. The closest thing I've found is JPA 2.0 @OrderColumn annotation in Hibernate 3.5, which looks a bit discouraging, given that it looks just like what I want to do.

Here is a rough sketch of what I'm trying to do, minus the annotations, since I'm not sure what they would be:

class Parent {
  // I probably need some sort of @OrderColumn annotation here, right?
  private List<Child> children = new ArrayList<Child>;
}

class Child {
  private Parent parent;
  private int order;
}

class SomeBusinessLogic {
  public static void createFamily() {
    Parent dad = new Parent("Tom");
    List<Children> children = dad.getChildren();
    children.add(new Child("Alice");
    children.add(new Child("Bob");
    children.add(new Child("Carl");
    session.save(dad);
  }

  public static void addChild(Parent parent) {  // assuming Tom is passed in
    List<Children> children = parent.getChildren();
    children.add(1, new Child("Zelda");
    session.save(parent);
    // now, the order should be: Alice, Zelda, Bob, Carl
  }
}

If someone can give me enough details to make this toy example work (or tell me that it will not work), I would be most appreciative.

Community
  • 1
  • 1
Josh Glover
  • 25,142
  • 27
  • 92
  • 129
  • 1
    This looks like a duplicate of [2902553](http://stackoverflow.com/q/2902553/851811). Take a look at `@OrderBy` – Xavi López Sep 15 '11 at 07:40
  • Xavi, I'm more interested in the automatic updating of the order column when I save the `Parent`. Adding an `@OrderColumn` annotation to `Parent` orders the children correctly when I get a `Parent` from the database, but I can't figure out how to persist a reordering. `@OrderBy` only handles the getting side of the problem, and thus won't suffice for me. – Josh Glover Sep 15 '11 at 07:51
  • Do you want to insert the collection in a given order? – ssedano Sep 15 '11 at 08:09
  • @Udo: Yes, I want the new child records to be inserted in the order of the children list. – Josh Glover Sep 15 '11 at 09:34

1 Answers1

1

In order to store children in its order you should map it with @IndexedColumn annotation it will create indexed column on your child objects table.

danny.lesnik
  • 18,479
  • 29
  • 135
  • 200