Mapping hibernation entities: extracting VARCHAR as Boolean

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

I displayed it 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 row because the column in the database is VARCHAR, however I would like to get it as java.lang.Boolean with Y / N deserialization.

Is there a way to do this using Hibernate annotations?

Thanks.

+1
java database hibernate hibernate-mapping
source share
1 answer

You can create your own matching type. Something like that:

 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 using the configuration:

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

and then use it in your essence:

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

Hope this helps.

+3
source share

All Articles