将空值加载到基本类型中
我正在尝试使用 ormlite 查询方法将数据库行加载到 DO 对象中。我面临的问题是数据库中的空值映射到 DO 对象中的包装类型字段。空字段作为 0 填充到 DO 中,这扰乱了我的业务逻辑。
有什么方法可以使 ormlite 将这些字段填充为 null 而不是 0。
我的示例 DO 结构:
@DatabaseTable(tableName="PERSON")
public class Person
{
@DatabaseField(columnName="NAME", dataType=DataType.STRING, useGetSet=true)
private String name;
@DatabaseField(columnName = "AGE", dataType = DataType.SHORT, useGetSet = true)
private Short age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Short getAge()
{
return age;
}
public void setAge(Short age)
{
this.age = age;
}
}
我用来加载对象的 DAO 代码是:
person = queryForEq("NAME", someName).get(0);
总结一下,在 Person 类中,如果人的年龄是在 SQLite 数据库中存储为 null,ormlite 在查询对象时填充为 0。我想避免这种情况并确保年龄设置为空。有什么办法可以达到这个目的吗?
I am trying to load a database row into a DO object using ormlite query methods. The problem I am facing is with the null values in the database which are mapped to a Wrapper type field in the DO object. The null fields are populated into the DO as 0 which messes up my business logic.
Is there any way possible to cause ormlite to populate these fields as null instead of 0.
My sample DO structure:
@DatabaseTable(tableName="PERSON")
public class Person
{
@DatabaseField(columnName="NAME", dataType=DataType.STRING, useGetSet=true)
private String name;
@DatabaseField(columnName = "AGE", dataType = DataType.SHORT, useGetSet = true)
private Short age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Short getAge()
{
return age;
}
public void setAge(Short age)
{
this.age = age;
}
}
The DAO code that I am using to load the objects is:
person = queryForEq("NAME", someName).get(0);
To summarise, in the Person class, if the age of person is stored as null in the SQLite database, ormlite is populating as 0 on querying the object. I want to avoid this and ensure the age is set as null. Is there any way to acheive this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里正确的做法是不要将
dataType
指定为@DatabaseField
注释的一部分。 ORMLite 将正确使用DataType.SHORT_OBJ
字段类型。由于您要覆盖默认字段类型并说Short
字段实际上是一个基元,因此如果 ORMLite did 为其分配 null,则会导致 NPE,因此它会分配0 代替。您的数据对象应该是:实际上,您永远不需要指定
dataType
除非您要覆盖某些内容或者 ORMLite 无法做出良好的自动类型确定(例如:byte[])。
The right thing to do here is to not specify the
dataType
as part of your@DatabaseField
annotation. ORMLite will then properly use theDataType.SHORT_OBJ
field type. Since you are overriding the default field type and saying that theShort
field is actually a primitive, if ORMLite did assign a null to it, it would cause a NPE so it assigns 0 instead. Your data object should instead be:Really you never need to specify the
dataType
unless you are overriding something or if ORMLite can't make a good automatic type determination (ex:byte[]
).