Oracle
 sql >> Database >  >> RDS >> Oracle

Spring JDBC BeanPropertyRowMapper sì no ('Y', 'N') alle proprietà booleane del bean

Quindi ho capito come farlo. Ho esteso i tipi booleani BeanPropertyRowMapper e handler tramite del codice personalizzato prima di trasferire il controllo a beanpropertyrowmapper per il resto dei tipi di dati.

Nota:funziona per me perché uso Oracle e tutte le colonne di tipo "booleano" sono stringhe con valori di tipo "y", "yes", "n" e "no".

Coloro che utilizzano 1,0 numerico o altri formati potrebbero potenzialmente migliorarlo ulteriormente rendendolo generico tramite una mappa di oggetti sì e ottenendo oggetti dal set di risultati e cercandoli in questa mappa. Spero che questo aiuti qualcun altro in una situazione come la mia.

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

/**
 * Extends BeanPropertyRowMapper to allow for boolean fields
 * mapped to 'Y,'N' type column to get set correctly. Using stock BeanPropertyRowMapper
 * would throw a SQLException.
 * 
 */
public class ExtendedBeanPropertyRowMapper<T> extends BeanPropertyRowMapper<T> {

    //Contains valid true values
    public static final Set<String> TRUE_SET = new HashSet<String>(Arrays.asList("y", "yes", "true"));

    public ExtendedBeanPropertyRowMapper(Class<T> class1) {
        super(class1);
    }

    @Override
    /**
     * Override <code>getColumnValue</code> to add ability to map 'Y','N' type columns to
     * boolean properties.
     * 
     * @param rs is the ResultSet holding the data
     * @param index is the column index
     * @param pd the bean property that each result object is expected to match
     * (or <code>null</code> if none specified)
     * @return the Object value
     * @throws SQLException in case of extraction failure
     * @see org.springframework.jdbc.core.BeanPropertyRowMapper#getColumnValue(java.sql.ResultSet, int, PropertyDescriptor) 
     */
    protected Object getColumnValue(ResultSet rs, int index,
            PropertyDescriptor pd) throws SQLException {
        Class<?> requiredType = pd.getPropertyType();
        if (boolean.class.equals(requiredType) || Boolean.class.equals(requiredType)) {
            String stringValue = rs.getString(index);
            if(!StringUtils.isEmpty(stringValue) && TRUE_SET.contains(stringValue.toLowerCase())){
                return true;
            }
            else return false;
        }       
        return super.getColumnValue(rs, index, pd);
    }
}