Monday, October 15, 2007

Moar Hibernate !!!

Yet again, I'm posting because of fucking hibernate. One of the old quirks I had run across was that if you had a setter for a collection, ie :

public void setItems(List items)
{
this.items = items;
}

...this would replace the hibernate-backed collection that already existed (if one did) and could replace it with a non-hibernate implementation such as java.util.Vector, and any cached items would not get properly dealt with, and the collection would not get properly persisted, even to the point of throwing an exception. This resulted in me having to change my setters to this :

public void setItems(List items)
{
if(this.items == null)
{
this.items = items;
} else
{
this.items.clear();
this.items.addAll(items);
}
}

The only problem with this is that depending on the scenario, hibernate gets the collection, and then sets exactly the same list object back into the persistent entity we're dealing with, which would result in clearing exactly the same list we're trying to assign. The remedy :

public void setItems(List items)
{
if(this.items == null)
{
this.items = items;
} else if(this.items != items) //fix: identity check the two lists!
{
this.items.clear();
this.items.addAll(items);
}
}

That really should have been there anyway, but hibernate inspired it. Fuck you hibernate.

No comments: