Issue
I have a problem with Lazy Initialization in Hibernate/J2EE. I have an Object Cat which contains an Object Collar which contains a String Address. Collar and Address are in Lazy Loading.
I'm working on my Object Cat, already loaded from my database (so my session is closed). My Cat does contain my Collar but I can access to my Address (Lazy loading exception).
So my idea was to reload Collar to get the Address. Its works, I do something like this:
Cat cat = animals.loadCat(id);
//Here, cat contains collar, but collar doesn't contains address
Collar collar = animals.reload(collar);
//Here my collar does contain my address
collar.setAddress("new address");
If I do a
animals.update(cat); //(a method who call merge)
It doesn't update the address, which seems logical.
If I do a
update(collar);
//Method update
public void update(Collar collar){
em.merge(collar);
}
It works and my Collar and Cat are updated in base.
public class Cat {
@ManyToOne
private Collar collar;
...
}
public class Collar {
@OneToMany(cascade = {CascadeType.ALL})
protected String address;
...
}
public Collar reload(Collar collar){
return em.find(Collar.class, collar.getId());
}
My question is, how to link my new collar to my cat, to do after a animals.update(cat)
?
Solution
Solution given by @Thomas :
Cat cat = animals.loadCat(id);
Collar collar = animals.reload(collar);
cat.setCollar(collar);
collar.setAddress("new address");
animals.update(cat);
I don't know if this is the best but it works and seems logic. Thanks to all
Answered By - Cyril Beslay