01: //$Id: DistinctRootEntityResultTransformer.java 3890 2004-06-03 16:31:32Z steveebersole $
02: package org.hibernate.transform;
03:
04: import java.util.ArrayList;
05: import java.util.HashSet;
06: import java.util.List;
07: import java.util.Set;
08:
09: import org.apache.commons.logging.Log;
10: import org.apache.commons.logging.LogFactory;
11:
12: /**
13: * @author Gavin King
14: */
15: public class DistinctRootEntityResultTransformer implements
16: ResultTransformer {
17:
18: private static final Log log = LogFactory
19: .getLog(DistinctRootEntityResultTransformer.class);
20:
21: static final class Identity {
22: final Object entity;
23:
24: Identity(Object entity) {
25: this .entity = entity;
26: }
27:
28: public boolean equals(Object other) {
29: Identity that = (Identity) other;
30: return entity == that.entity;
31: }
32:
33: public int hashCode() {
34: return System.identityHashCode(entity);
35: }
36: }
37:
38: public Object transformTuple(Object[] tuple, String[] aliases) {
39: return tuple[tuple.length - 1];
40: }
41:
42: public List transformList(List list) {
43: List result = new ArrayList(list.size());
44: Set distinct = new HashSet();
45: for (int i = 0; i < list.size(); i++) {
46: Object entity = list.get(i);
47: if (distinct.add(new Identity(entity))) {
48: result.add(entity);
49: }
50: }
51: if (log.isDebugEnabled())
52: log.debug("transformed: " + list.size() + " rows to: "
53: + result.size() + " distinct results");
54: return result;
55: }
56:
57: }
|