|
| 1 | +package com.vladmihalcea.book.hpjp.hibernate.fetching.pagination; |
| 2 | + |
| 3 | +import com.vladmihalcea.book.hpjp.hibernate.identifier.Identifiable; |
| 4 | +import org.hibernate.transform.BasicTransformerAdapter; |
| 5 | + |
| 6 | +import java.io.Serializable; |
| 7 | +import java.util.*; |
| 8 | + |
| 9 | +/** |
| 10 | + * @author Vlad Mihalcea |
| 11 | + */ |
| 12 | +public class DistinctPostResultTransformer extends BasicTransformerAdapter { |
| 13 | + |
| 14 | + public static final DistinctPostResultTransformer INSTANCE = new DistinctPostResultTransformer(); |
| 15 | + |
| 16 | + @Override |
| 17 | + public List transformList(List list) { |
| 18 | + Map<Serializable, Identifiable> identifiableMap = new LinkedHashMap<>(list.size()); |
| 19 | + for (Object entityArray : list) { |
| 20 | + if (Object[].class.isAssignableFrom(entityArray.getClass())) { |
| 21 | + Post post = null; |
| 22 | + PostComment comment = null; |
| 23 | + |
| 24 | + Object[] tuples = (Object[]) entityArray; |
| 25 | + |
| 26 | + for (Object tuple : tuples) { |
| 27 | + if (tuple instanceof Post) { |
| 28 | + post = (Post) tuple; |
| 29 | + } else if (tuple instanceof PostComment) { |
| 30 | + comment = (PostComment) tuple; |
| 31 | + } else { |
| 32 | + throw new UnsupportedOperationException( |
| 33 | + "Tuple " + tuple.getClass() + " is not supported!" |
| 34 | + ); |
| 35 | + } |
| 36 | + } |
| 37 | + Objects.requireNonNull(post); |
| 38 | + Objects.requireNonNull(comment); |
| 39 | + |
| 40 | + if (!identifiableMap.containsKey(post.getId())) { |
| 41 | + identifiableMap.put(post.getId(), post); |
| 42 | + post.setComments(new ArrayList<>()); |
| 43 | + } |
| 44 | + post.addComment(comment); |
| 45 | + } |
| 46 | + } |
| 47 | + return new ArrayList<>(identifiableMap.values()); |
| 48 | + } |
| 49 | +} |
0 commit comments