Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate entities mapping: Retrieve VARCHAR as boolean

I have a table INCIDENCIA in my database that has a VARCHAR column VISIBLE with two possible values: Y or N matching true or false.

I have it mapped in this entity:

@Entity
public class Incidencia {

    private String visible;

    //other fields

    @Basic
    @Column(name = "VISIBLE")
    public String getVisible() {
        return visible;
    }

    public void setVisible(String visible) {
        this.visible = visible;
    }
}

This field is a String since column in database is a VARCHAR, however I would like to retrieve it as java.lang.Boolean with a Y/N deserialization.

Is there any way to do this by Hibernate annotations?

Thanks.

like image 495
Héctor Avatar asked Oct 14 '25 08:10

Héctor


1 Answers

You can create your own mapping type. Something like this:

package es.buena.jamon.type;

public class SpanishBoolean  extends AbstractSingleColumnStandardBasicType<Boolean> 
              implements PrimitiveType<Boolean>, DiscriminatorType<Boolean> 
{
    private static final long serialVersionUID = 1L;
    public static final SpanishBoolean INSTANCE = new SpanishBoolean(); 


    public SpanishBoolean() { 
            super( CharTypeDescriptor.INSTANCE, new BooleanTypeDescriptor('S', 'N') ); 
    } 
    @Override 
    public String getName() { 
            return "si_no"; 
    } 
    @Override 
    public Class getPrimitiveClass() { 
            return boolean.class; 
    } 
    @Override 
    public Boolean stringToObject(String xml) throws Exception { 
            return fromString( xml ); 
    } 
    @Override 
    public Serializable getDefaultValue() { 
            return Boolean.FALSE; 
    } 
    @Override 
    public String objectToSQLString(Boolean value, Dialect dialect) throws Exception { 
            return StringType.INSTANCE.objectToSQLString( value ? "S" : "N", dialect ); 
    } 
}

and then register it with the configuration:

Configuration configuration = new Configuration().configure();
configuration.registerTypeOverride(new SpanishBoolean());

and then use it in your entity:

@Type(type="es.buena.jamon.type.SpanishBoolean")
private Boolean visible;

Hope that helps.

like image 170
raminr Avatar answered Oct 18 '25 02:10

raminr



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!