本文介绍了Hibernate实体映射:将VARCHAR检索为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在我的数据库中有一个具有两个可能值的VARCHAR列 VISIBLE
的表 INCIDENCIA
: Y
或 N
匹配 true
或 false
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
.
我已在此实体中映射:
@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;
}
}
此字段是一个字符串,因为数据库中的列是VARCHAR,但是我想检索它作为java.lang.Boolean与Y / N反序列化。
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.
有什么方法可以通过Hibernate注释来做到这一点?
Is there any way to do this by Hibernate annotations?
谢谢。
推荐答案
您可以创建自己的映射类型。这样的东西:
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 );
}
}
,然后使用配置注册:
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;
希望有帮助。
这篇关于Hibernate实体映射:将VARCHAR检索为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!