views:

50

answers:

2

Is it possible to have a static collection as a member of a hibernate entity?

Say I have an object Question:

public class Question {
    private String category;

    ...
}

Would it be possible to populate a static Set<String> that is a distinct set of all categories in the Database? I know I could just query this, but I was wondering if there was a more elegant solution, as it seems like something that other people may have come across.

+1  A: 

To my knowledge, JPA cannot persist static or final fields. The spec isn't very clear on this but it makes IMO sense since I don't see what would be the one in a OneToXXX relation (so how should JPA load it). You might want to check the following thread for some feedback (i.e. not a final answer) from the ejb3 expert group. I'm afraid you'll have somehow to link all your Question with all Category.

But maybe you'll get more "satisfying" answers. Let's see.

Pascal Thivent
I meant along the lines of a read only collection that pulled from a SELECT DISTINCT query.
partkyle
@Kyle Yeah, I understand the idea but I don't know how to tell JPA to do that in a nice way. I'm very curious to see if you get better answers.
Pascal Thivent
+1  A: 

Simple but not perfect solution would be using entity @PostLoad callback method on Category or Question entities (or both):

@Entity
public class Question {
  public static Set<String> categories = new HashSet<String>();
  ...

  @PostLoad
  public void fillInCategories() {
    categories.add(category);
  }

}

categories is lazy loaded - until all questions that contain every category are loaded it won't be complete.

grigory