Hibernate: Custom Collection Types
At 11:50 PM on Apr 19, 2005, R.J. Lorimer
wrote:
On Monday's tip ( Hibernate: Discriminators and Table-Per-Subclass ) it was claimed by a reader that one major failing of Hibernate was that you couldn't inject your own collection types when faced with a list, set, map, or other collection mapping in your hibernate mapping file. As of Hibernate 3 this statement is 100% wrong. While there is a small degree of effort on your part, it is most-decidedly possible. I plan to show you how today (as I couldn't leave it alone myself).
The first step is to implement the org.hibernate.usertype.UserCollectionType interface. This API helps hibernate work with your collection without concern of the implementation. Truthfully, Hibernate doesn't care at all what API your collection implementation actually implements - it could be a com.Javalobby.tnt.WidgerFurmuzzitContainer , and Hibernate could still map it. However, my goal here is to show you how to replace a default implementation with a custom one.
Since I have no implementation of java.util.Set to use, I'll just refer to the Javolution javolution.util.FastSet , which has the benefit of being arguably faster than a standard set implementation.
Here is an implementation of UserCollectionType that returns a fast set. As you are looking below, note how much possibility there is for common subclasses that provide custom set/list/map implementations:
package com.javalobby.tnt.hib;
import java.util.*;
import javolution.util.FastSet;
import org.hibernate.HibernateException;
import org.hibernate.collection.*;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.persister.collection.CollectionPersister;
import org.hibernate.usertype.UserCollectionType;
public class FastSetType implements UserCollectionType {
public FastSetType() {
}
// could be common for all collection implementations.
public boolean contains(Object collection, Object obj) {
Set set = (Set)collection;
return set.contains(obj);
}
// could be common for all collection implementations.
public Iterator getElementsIterator(Object collection) {
return ((Set)collection).iterator();
}
// common for list-like collections.
public Object indexOf(Object collection, Object obj) {
return null;
}
// factory method for certain collection type.
public Object instantiate() {
return new FastSet();
}
// standard wrapper for collection type.
public PersistentCollection instantiate(SessionImplementor session, CollectionPersister persister) throws HibernateException {
// Use hibernate's built in persistent set implementation
//wrapper
return new PersistentSet(session);
}
// could be common implementation for all collection implementations
public文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!


