Reputation: 4040
I have a business object that exposes a list of elements for which want to have control on.
For that, I have created a custom List implementation (CustomList) with a listener to be notified whenever an an element added / removed.
public class MyClass {
private List<ItemClass> list;
public MyClass() {
this.list = new CustomList<ItemClass>();
}
public List<ItemClass> getList() {...}
public setList(List<ItemClass>) {...}
}
The problem is that, if I want to persist this object, Hibernate uses the setter to set the list with its own List implementation, thus short-circuiting my nice CostumList bahavior.
I have tried to cheat with the setter, this way :
public setList(List<ItemClass> newList) {
this.list.clean():
this.list.addAll(newList);
}
But this does not work either : Hibernate calls the setter first, and then add some elements to its own list. Therefore, I end up with an empty list on my side.
Is there a way I can ask hibernate to use my custom list implementation ? Or to fill it after has loaded the contents ?
Thanks in advance for your help.
Upvotes: 3
Views: 1260
Reputation: 336
My first thought was to do something like this:
You could always use the setter to change the list implementation (similar to what you have done). For instance:
public setList(List<ItemClass> newList) { // Sets the list as a custom list. list = new CustomList<>(newList); }
Yet, for that to work, you need to change the implementation of your CustomList to work as a decorator, so it will work independently of the wrapped list type.
As @millimoose has noticed, it still does not solve your problem.
A working solution could be found by using the Hibernate (or JPA) lifecycle annotations (such as @PostPersist, @PostUpdate or @PostLoad...). So, you could use that customList.addAll() solution (after the entity has been updated, persisted or loaded).
Upvotes: 2