this question is similar to this other question I’ve asked, but slightly different.
I have this:
class A{
private List<B> bs;
...
}
class B{
private Long id;
private C c;
...
}
class C{
private Long id;
private String name;
...
}
And I’d like to have this:
class A{
// the map should have b.c.name as key
private Map<String,B> bs;
...
}
class B{
private Long id;
private C c;
private A a;
...
}
class C{
private Long id;
private String name;
...
}
I don’t know if it is clear what I’d like to do, but it is as simple as mapping a one to many relationship to a Map with the name of C as the key of the map and b as the value.
Thanks in advance,
Neuquino
Short answer is you can’t do this.
But a here is solution that may be suitable for your problem:
In entity A still defined relation to entity B as List (or even better as Set, so that the same B cannot be contained more than once).
As you don’t want to expose the plain list, omit getter and setter for
as.Then you can define a getter for you map that builds the map on the fly:
The last issue to address is how do we add a new B to A or remove one. With the strategy to return the map as unmodifiable, we must provide some add and remover methods in class A:
An other option is to replace
return Collections.unmodifiableMap(...)with (inspired from ObservaleCollection from apache):