Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an order Map wih AliasToEntityMapResultTransformer ?

I've used this stuff to get a List>, which is very interesting to manipulate datas like a "resultSet". My method is : requeteSQL.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);

When i execute this query with sqldevelopper, i have got for exemple | Field 1 | Field 2 Line 1 | Value 1 | Value 2

But my map is not in the righ order ? How to fix this error ? And why my map have Field2 = Value2, Field1 = Value1 in this order ?

like image 388
user2114638 Avatar asked Dec 02 '25 06:12

user2114638


1 Answers

because it hash map, how can you expect the order retrieval,if want order retrieval please implement your own ResultTransformer which will return LinkedHashMap e.g.

public class AliasToEntityOrderedMapResultTransformer extends AliasedTupleSubsetResultTransformer {

public static final AliasToEntityOrderedMapResultTransformer INSTANCE = new AliasToEntityOrderedMapResultTransformer();

/**
 * Disallow instantiation of AliasToEntityOrderedMapResultTransformer .
 */
private AliasToEntityOrderedMapResultTransformer () {
}

/**
 * {@inheritDoc}
 */
public Object transformTuple(Object[] tuple, String[] aliases) {
            /* please note here LinkedHashMap is used so hopefully u ll get ordered key */
    Map result = new LinkedHashMap(tuple.length);
    for ( int i=0; i<tuple.length; i++ ) {
        String alias = aliases[i];
        if ( alias!=null ) {
            result.put( alias, tuple[i] );
        }
    }
    return result;
}

/**
 * {@inheritDoc}
 */
public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
    return false;
}

/**
 * Serialization hook for ensuring singleton uniqueing.
 *
 * @return The singleton instance : {@link #INSTANCE}
 */
private Object readResolve() {
    return INSTANCE;
}
}

by the way your logic should not be depend of the order of keys it appear in resultant map.

like image 171
Jitendra Vispute Avatar answered Dec 04 '25 19:12

Jitendra Vispute



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!