How to handle Target Unreachable in an elegant way
I have 2 questions regarding the so common Target Unreachable Exception. What's the best practice to handle it, for example you have: Country has City, City has Street. - do you put in Country's constructor new City(), and in City's constructor new Street() (so that you开发者_如何学JAVA somehow have them into a centralized place, but always make objects which you might not need) OR you initialize the objects in various places in your code where you need them ? (spread all over your code) - and if the user doesn't type anything say for Street, in order to prevent the insertion of a blank row in the DB you put the street back to null. Where's the best place to put it back to null ? (say you have Cascade.ALL or Extended Context, otherwise you'd just not save it if you knew it's empty)
PS: why isn't JSF just instantiating what it needs, and Hibernate not persisting entities that have all persistent fields empty ? For performance or why ? Yet again, is it bad to have empty rows in db, just with PK and FKs ?
I think it depends on the relationship between the entities in your app. In some cases I do load a related instance of another object in the constructor but only in the case where you wouldn't have one entity without the other.
One alternative is to create the objects lazily in the getter:
public class Country {
private City city;
public City getCity() {
if (this.city == null) {
this.city = new City();
}
return this.city;
}
}
As far as the PS questions JSF doesn't instantiate objects for you -- I'm not sure that would be desirable ... but if you use the lazy getter approach you effectively get the same thing. Hibernate persists an entity if it has been instantiated since it persists the current state of the persistable object model and if it didn't persist that entity it wouldn't be working as expected.
I typically don't worry about a few null rows as I choose to use Hibernate knowing that an ORM comes with some small cost in performance. To me it is still well worth it to enjoy the abstraction of persistence.
精彩评论