[#8390] Add support for unmapping Iterable

This commit is contained in:
lukaseder 2019-03-06 12:39:07 +01:00
parent 70fe064517
commit 726e77960a
2 changed files with 38 additions and 1 deletions

View File

@ -1045,6 +1045,12 @@ public interface Record extends Attachable, Comparable<Record>, Formattable {
* <p>
* Loading of data is delegated to {@link #fromMap(Map)}
* <p>
* <h5>If <code>source</code> is an {@link Iterable}</h5>
* <p>
* <p>
* Loading of data is equivalent to loading {@link #fromArray(Object...)},
* transforming the {@link Iterable} to an array, first.
* <p>
* <h5>If any JPA {@link Column} annotations are found on the {@link Class}
* of the provided <code>source</code>, only those are used. Matching
* candidates are:</h5>
@ -1063,7 +1069,8 @@ public interface Record extends Attachable, Comparable<Record>, Formattable {
* <li>{@link Column#name()} must match {@link Field#getName()}. All other
* annotation attributes are ignored</li>
* <li>Only the first match per field is used</li>
* <li>Matching methods have a higher priority than matching member fields</li>
* <li>Matching methods have a higher priority than matching member
* fields</li>
* <li>Explicitly matching methods have a higher priority than implicitly
* matching methods (implicitly matching getter = setter is annotated)</li>
* <li>Static methods / member fields are ignored</li>

View File

@ -44,6 +44,7 @@ import static org.jooq.impl.Tools.getMatchingMembers;
import static org.jooq.impl.Tools.hasColumnAnnotations;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@ -90,6 +91,8 @@ public class DefaultRecordUnmapper<E, R extends Record> implements RecordUnmappe
delegate = new ArrayUnmapper();
else if (Map.class.isAssignableFrom(type))
delegate = new MapUnmapper();
else if (Iterable.class.isAssignableFrom(type))
delegate = new IterableUnmapper();
else
delegate = new PojoUnmapper();
}
@ -166,6 +169,33 @@ public class DefaultRecordUnmapper<E, R extends Record> implements RecordUnmappe
}
}
private final class IterableUnmapper implements RecordUnmapper<E, R> {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public final R unmap(E source) {
if (source == null)
return null;
if (source instanceof Iterable) {
Iterator<?> it = ((Iterable<?>) source).iterator();
int size = rowType.size();
Record record = newRecord();
for (int i = 0; i < size && it.hasNext(); i++) {
Field field = rowType.field(i);
if (rowType.field(field) != null)
Tools.setValue(record, field, it.next());
}
return (R) record;
}
throw new MappingException("Iterable expected. Got: " + source.getClass());
}
}
private final class MapUnmapper implements RecordUnmapper<E, R> {
@SuppressWarnings("unchecked")