package com.mysema.query.sql.types;

import javax.annotation.Nullable;
import java.sql.*;

/**
 *
 * @param <T>
 */
public class ArrayType<T> extends AbstractType<T> {

    private static void copy(Object source, Object target, int length) {
        // Note: System.arrayCopy doesn't handle copying from/to primitive arrays properly
        for (int i = 0; i < length; i++) {
            Object val = java.lang.reflect.Array.get(source, i);
            java.lang.reflect.Array.set(target, i, val);
        }
    }

    private final Class<T> type;

    private final String typeName;

    public ArrayType(Class<T> type, String typeName) {
        super(Types.ARRAY);
        this.type = type;
        this.typeName = typeName;
    }

    @Override
    public Class<T> getReturnedClass() {
        return type;
    }

    @Nullable
    @Override
    public T getValue(ResultSet rs, int startIndex) throws SQLException {
        Array arr = rs.getArray(startIndex);
        if (arr != null) {
            Object[] rv = (Object[])arr.getArray();
            if (!type.isAssignableFrom(rv.getClass())) {
                Object rv2 = java.lang.reflect.Array.newInstance(type.getComponentType(), rv.length);
                copy(rv, rv2, rv.length);
                return (T) rv2;
            } else {
                return (T) rv;
            }

        } else {
            return null;
        }
    }

    @Override
    public void setValue(PreparedStatement st, int startIndex, T value) throws SQLException {
        if (!type.isAssignableFrom(value.getClass())) {

        }
        Array arr = st.getConnection().createArrayOf(typeName, (Object[])value);
        st.setArray(startIndex, arr);
    }
}

@@ -84,16 +84,65 @@
 sql.*;%0A%0A
+import com.google.common.primitives.Primitives;%0A%0A
 /**%0A *%0A 
@@ -623,24 +623,70 @@
  typeName;%0A%0A
+    private final boolean convertPrimitives;%0A%0A
     public A
@@ -816,16 +816,88 @@
 peName;%0A
+        this.convertPrimitives = type.getComponentType().isPrimitive();%0A
     %7D%0A%0A 
@@ -1224,48 +1224,62 @@
 if (
-!type.isAssignableFrom(rv.getClass())) %7B
+convertPrimitives) %7B%0A                // primitives out
 %0A   
@@ -1513,25 +1513,24 @@
           %7D%0A
-%0A
         %7D el
@@ -1700,52 +1700,311 @@
 if (
-!type.isAssignableFrom(value.getClass())) %7B%0A
+convertPrimitives) %7B%0A            // primitives in%0A            int length = java.lang.reflect.Array.getLength(value);%0A            Object value2 = java.lang.reflect.Array.newInstance(Primitives.wrap(type.getComponentType()), length);%0A            copy(value, value2, length);%0A            value = (T)value2;
 %0A   

Improve conversion