How can I make a POJO that's referenced in another POJO read-only?
Take this situation:
Code:
public class Level1 {
int id;
Level2 level2;
// necessary getters/setters and annotations
}
public class Level2 {
int id;
Level3 level3;
// necessary getters/setters and annotations
}
public class Level3 {
int id;
int value;
// necessary getters/setters and annotations
}
I get a 'Level1' object from database, set Level1.level2.level3 to null:
Code:
Level1 level1 = (Level1) session.createQuery("from Level1 l where l.level1id = 1").uniqueResult();
Level2 level2 = level1.getLevel2();
level2.setLevel3(null);
result: POJO 'Level2' is updated and I don't want that.
If I use session.createQuery("...")
.setReadOnly(true).uniqueResult() then the 'Level1' POJO is protected but not any dependent objects.
If I try
session.setReadOnly(level2, true) I get an exception:
org.hibernate.TransientObjectException: Instance was not associated with the session
So, how can I make dependent objects read-only?
(Note: In our production code we use
Session.clear() at the end of the method in which we have manipulated our POJOs to discard any changes we may have made. This method might be called from other methods that may change the POJO even further.
This approach works in Hibernate 3.2.3 but not in any higher version. We're getting a
org.hibernate.LazyInitializationException: could not initialize proxy - no Session. Apparently it is suppose the be that way (link to
bug report). Thus, it's a bug in the older versions. This is really bad because we created a lot of code that relies on the clear()-method.)