java 如何使用JDBI注解将聚合查询结果选择为元组?

k5ifujac  于 5个月前  发布在  Java
关注(0)|答案(3)|浏览(41)

我正在使用JDBI,我需要使用聚合函数运行查询。
我该如何阅读这个查询的结果?我可以使用什么返回类型来方便它?

@SqlQuery("select count(*), location from Customers group by location")
public Type getCustomersCountByLocation();

字符串
我可能会向聚合函数结果添加一个别名,并编写一个匹配的POJO

@SqlQuery("select count(*) as customerCount, location from Customers group by location")
public List<CustomerLocation> getCustomersCountByLocation();


POJO是:

public class CustomerLocation {

    private int customerCount;

    private String location;

    public CustomerLocation(int customerCount, String location) {
        this.customerCount = customerCount;
        this.location = location;
    }

    //getters
}


我可以为这类查询编写一个通用的对象,但这会引入不必要的耦合。
JDBI是否支持任何类型的OOTB,允许我将查询的结果选择到一个用正确类型参数化的任意n元组中?
伪代码:

@SqlQuery("select count(*) as customerCount, location from Customers group by location")
public List<Tuple<Integer, String>> getCustomersCountByLocation();

yyhrrdl8

yyhrrdl81#

other answer是一个非常好的,但我只是想发布一个回答具体问题是有人想知道。
Manikandan的建议可以用org.apache.commons.lang3.tuple.Pair来完成。

@SqlQuery("select count(*) as customerCount, location from Customers group by location")
@Mapper(CustomerCountByLocationMapper.class)
public List<Pair<String, Integer>> getCustomersCountByLocation();

字符串
然后在mapper类中:

public class CustomerCountByLocationMapper implements ResultSetMapper<Pair<String, Integer>> {

    @Override
    public Pair<String, Integer> map(int index, ResultSet r, StatementContext ctx) throws SQLException {
        String location = r.getString("location");
        Integer customerCount = r.getInt("customerCount");
        return Pair.of(source, count);
    }
}


在这种情况下,getCustomersCountByLocation方法将返回一个List<Pair<String,Integer>>,正如另一个答案所指出的,这是一个愚蠢的类型,具有这种语义的对列表实际上是一个Map。
同时,ResultSetMapper接口足够灵活,允许Map到完全任意的类型。在一个更合适的上下文中,Pair只需要几行代码就可以使用。

wsewodh2

wsewodh22#

你可以使用Map代替。你只需要写一次mapper,它可以用于所有聚合查询,也可以用于其他用例。

@SqlQuery("select count(*) as customerCount, location from Customers group by location")
@Mapper(MapMapper.class)
public Map getCustomersCountByLocation();

字符串
并像这样定义mapper。

public class MapMapper implements ResultSetMapper<Map<String, Integer>> {
    @Override
    public Map<String, Integer> map(int index, ResultSet r, StatementContext ctx) throws SQLException {
        HashMap<String, Integer> result = new HashMap<>();
        for(int i =1; i <= r.getMetaData().getColumnCount(); i++) {
            String columnName = r.getMetaData().getColumnName(i);
            Integer value = r.getInt(i);
            result.put(columnName, value);
        }
        return result;
    }
}

yebdmbv4

yebdmbv43#

现在,正如我发现的,我们可以使用内置的org.skife.jdbi.v2.DefaultMapper(至少在v2.78+中),然后在客户端将obj转换为int,例如:

@SqlQuery("select count(*) as customerCount, location from Customers group by location")
@Mapper(DefaultMapper.class)
public List<Map<String, Object>> getCustomersCountByLocation();
...
int count = Integer.valueOf(dbRes.get(0).get("customerCount"))

字符串

相关问题