Hibernate entities mapping: Retrieve VARCHAR as boolean

别说谁变了你拦得住时间么 提交于 2019-12-08 06:56:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28851462/hibernate-entities-mapping-retrieve-varchar-as-boolean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!