Cast Entity association collection to implementation type

Discussions

EJB programming & troubleshooting: Cast Entity association collection to implementation type

  1. Persistence Provider: JBoss Hibernate I have an entity with a one-to-many association. For my business logic, I want the collection implementation type to be a TreeSet as I can sort it. @Entity public class Foo1 { @Id private Long id; @OneToMany(mappedBy="foo1"); Set foo2s; public void addFoo2(Foo2 foo2) { if (foo2s == null) { this.foo2s = new TreeSet(); } this.foo2s.add(foo2); } ... } Let's say I persist the entity and so it becomes managed. When the entity becomes managed, the persistence provider replaces the collection implementation with its custom implementation org.hibernate.collection.PersistentSet. Now if I do any TreeSet operation on my collection, it does not work as the collection implementation type is not a TreeSet anymore. foo1.getFoo2s().first() //throws exception. But I do want my collection implementation to be a TreeSet even in a managed entity. I know I can not cast org.hibernate.collection.PersistentSet to java.util.TreeSet. Why do we have such restriction in implementation? Why can't the persistence provider (Hibernate) use TreeSet as the implementation type? I do not want my code to be dependent on vendor-specific implementation like PersistentSet or PersistentSortedSet. Is there a solution to this? Is there a way to use a java.util.* collection implementation in a managed entity? I would appreciate any help. Thanks Vignesh
  2. Use SortedSet instead of Set. try SortedSet foo2s;
  3. Thanks for your reply. I did try SortedSet earlier but it throws exception on server startup. Illegal attempt to map a non collection as a @OneToMany It does not allow to declare anything other than root java.util collection interface type ie., Collection, Set, Map and List. Earlier I did not mention that I am using Hibernate implementation of JPA.