I'm still learning the do's and don'ts about Hibernate and I had a question. It has to do with persisting collections and cascading. Here's my pseudo-code:
Code:
Main Entity Class:
...
@OneToMany (
mappedBy = "mainEntity",
targetEntity = Things.class,
fetch = FetchType.EAGER,
cascade = CascadeType.ALL
)
private List<Things> things= new ArrayList<Things>();
...
Collection Entity Class:
...
@ManyToOne @JoinColumn(name = "main_entity_id")
private MainEntity mainEntity;
...
Now, when I go to update values in the things collection inside the MainEntity class, nothing happens. My code to add values to the List is this:
Code:
mainEntity.getThings().add(value);
mainEntity.getThings().addAll(values);
When I do this, nothing happens as far as Hibernate is concerned. Yes, the Things objects are added to the transient MainEntity class, but not to the database in any way. So, I have to call this:
Code:
mainEntity.getThings().addAll(values);
List<Things> thingList = new ArrayList<Things>();
for (Things thing : mainEntity.getThings()) {
thing.setMainEntity(mainEntity);
thingList.add(thing);
}
mainEntity.setThings(thingList);
myDao.update(mainEntity);
whenever I make an update to the collection values. Kind of a bit of a workaround, wouldn't you say?
Now, if I omit this code and just call update after adding values to the mainEntity.getThings() List, I get a Transient Object Exception (HibernateException) saying that the added Things don't belong to the mainEntity instance or something like that.
To prevent redundancy and wasting of time, is there a way I can do this without having to define all of this for every collection I persist?