'JPA Set of Set of Entity

Is there a possibility to achieve a set of sets of some specific entity? If yes, how do I need to annotate that field? My java class looks the following:

class Foo {
  long id;
  int value;
  Set<Set<Bar>> barSets;
}

class Bar {
  long id;
  String name;

  String toString() { return name; }
}

My database tables are specified as following:

CREATE TABLE foo (
  id LONG PRIMARY KEY,
  value INTEGER
);

CREATE TABLE bar (
  id LONG PRIMARY KEY,
  name TEXT
);

CREATE TABLE foo_bar (
  foo_id LONG REFERENCES foo,
  set_index INTEGER,
  bar_id LONG REFERENCES bar
);

The set_index of the foo_bar table defines which entries belong together within the same foo element. Maybe there is also some better approach to achieve this?

Example:

foo:
id | value
---|------
 1 | 100 
 2 | 200

bar:
id | name
---|------
 1 | AAA 
 2 | BBB
 3 | CCC

foo_bar:
foo_id | set_index | bar_id
-------|-----------|-------
     1 |         1 |      1
     1 |         1 |      2
     1 |         2 |      1
     1 |         2 |      3
     2 |         1 |      2
     2 |         1 |      3

Java objects:

  • Foo { id=1, value=100, bars=[ [AAA, BBB], [AAA, CCC] ] }
  • Foo { id=2, value=200, bars=[ [BBB, CCC] ] }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source