I was having problems today with lazy loading not working when using a mapped by collection. I found this excellent article that seems to fix the problem
http://justonjava.blogspot.co.uk/2010/09/lazy-one-to-one-and-one-to-many.html
One thing I do not understand is how the workaround using FieldHandled works. Can anyone help me understand this? The code in question is below (copied from the example on the link):
@Entity
public class Animal implements FieldHandled {
private Person owner;
private FieldHandler fieldHandler;
@OneToOne(fetch = FetchType.LAZY, optional = true, mappedBy = "animal")
@LazyToOne(LazyToOneOption.NO_PROXY)
public Person getOwner() {
if (fieldHandler != null) {
return (Person) fieldHandler.readObject(this, "owner", owner);
}
return owner;
}
public void setOwner(Person owner) {
if (fieldHandler != null) {
this.owner = fieldHandler.writeObject(this, "owner", this.owner, owner);
return;
}
this.owner = owner;
}
public FieldHandler getFieldHandler() {
return fieldHandler;
}
public void setFieldHandler(FieldHandler fieldHandler) {
this.fieldHandler = fieldHandler;
}
}
What am I missing? Perhaps I dont know enough about hibernate's lifecycle here? Im happy to investigate but can anyone give me some pointers.
Thanks in advance.
EDIT
I pushed through a lot of changes so a lot of my entities implemented FieldHandled but then discovered some of my tests were failing. I pumped out the SQL and got some weird things where the SQLs were happening in different orders if this interface was implemented with just these methods set.
public FieldHandler getFieldHandler() {
return fieldHandler;
}
public void setFieldHandler(FieldHandler fieldHandler) {
this.fieldHandler = fieldHandler;
}
This was causing tests to fail as things were not quite in the correct state when I was asserting. This adds to my mis-understanding of this FieldHandler variable.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…