如何在iBatis中返回NULL值? [英] How to Return NULL-values in iBatis?
问题描述
假设我有一个Oracle数据库和一个类似这样的接口:
Let's say I have an Oracle database and an interface like this:
public interface DaoMapper {
@Select({
"SELECT col1, col2, col3",
"FROM my_table" })
List<Map<String, Object>> getUntyped();
}
如果我调用getUntyped()
,并且所有列都有一个值,则映射包含三个条目.但是,如果col2
为NULL
,则映射仅具有两个条目.在很多情况下,这不是问题,但是在我们代码的通用部分中,我实际上想在该地图上调用.values()
,并希望包含三个条目的列表.任何条目都可以为null
(或与Oracle中相同的空字符串).
If I call getUntyped()
and all columns have a value the map contains three entries. However, if col2
is NULL
, the map has only two entries. In many cases this isn't a problem, but in a generic part of our code I actually want to call .values()
on that map and want a list consisting of three entries. Any entry may be null
(or an empty string as that's the same in Oracle).
实际上,我真的很高兴这样的事情,其中每个外部列表都由具有三个条目的列表组成:
Actually, what I would be really happy about is something like this where each outer list consists of lists with three entries:
@Select({
"SELECT col1, col2, col3",
"FROM my_table" })
List<List<Object>> getUntypedList();
但是,iBatis告诉我这是一项不受支持的操作.
However, iBatis tells me that this is an unsupported operation.
因此,我在这里问我如何告诉iBatis包含NULL
或空字符串的列.
Therefore, I'm here to ask how I can tell iBatis to include columns that are NULL
or an empty string.
推荐答案
Thanks to Giovanni's answer I noticed the example for type handlers and went from there:
public class EmptyStringTypeHandler extends StringTypeHandler {
@Override
public String getResult(ResultSet rs, String columnName) throws SQLException {
return unnulledString(super.getResult(rs, columnName));
}
@Override
public String getResult(ResultSet rs, int columnIndex) throws SQLException {
return unnulledString(super.getResult(rs, columnIndex));
}
@Override
public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
return unnulledString(super.getResult(cs, columnIndex));
}
private String unnulledString(String value) {
return StringUtils.defaultString(value, "");
}
}
界面现在为:
public interface DaoMapper {
@Select({
"SELECT col1, col2, col3",
"FROM my_table" })
@Results(value = {
@Result(column = "col1", property = "col1", typeHandler = EmptyStringTypeHandler.class),
@Result(column = "col2", property = "col2", typeHandler = EmptyStringTypeHandler.class),
@Result(column = "col3", property = "col3", typeHandler = EmptyStringTypeHandler.class)
})
List<LinkedHashMap<String, ?>> getUntyped();
}
我应该补充一点,最大的好处是我可以在每条语句的每一列中指定它.对于更通用的用法,最好在每个语句中指定它.也许是将来的版本?
I should add that the big advantage is that I can specify this per column per statement. For more generic use it would be better to specify this per statement. Maybe in some future version?
这篇关于如何在iBatis中返回NULL值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!