0

我希望我的 Java 层使用存储过程与我的数据库通信。存储过程充当兼容层,因此我可以运行两个不同版本的应用程序,期望在同一个数据库上使用两个不同的模式。

为此,我想使用 Orika 将 JDBC ResultSet 快速映射到我的 Beans 上。

到目前为止,我已经编写了这个测试代码:@Test public void testSelectAndMap() throws Exception { Assert.assertNotNull(dataSource); 尝试(连接 con = dataSource.getConnection()) { try(Statement stmt = con.createStatement()) {

            try (ResultSet result = stmt.executeQuery("select 1 as internalTestPojoId, CURRENT_TIMESTAMP as now")) {
                result.next();
                MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
                mapperFactory.classMap(ResultSet.class, InternalTestPojo.class)
                        .byDefault()
                        .field("internalTestPojoId:{getInt('internalTestPojoId')|getInt('internalTestPojoId')|type=" + int.class.getName() + "}", "internalTestPojoId")
                        .field("now:{getTimestamp('now')|getTimestamp('now')|type=" + Timestamp.class.getName() + "}", "now")
                        .register();
                MapperFacade mapper = mapperFactory.getMapperFacade();
                InternalTestPojo pojo = mapper.map(result, InternalTestPojo.class);
                Assert.assertEquals(pojo.internalTestPojoId, 1);
                Assert.assertEquals(pojo.now, new Timestamp(new Date().getTime() / 1000 * 1000));

            }

这很好用,速度很快,但是我编写 ResultSet 到 Bean 代码所花费的时间并没有少多少。但如果我能自动生成映射,它会为我节省很多时间。

我看着IntrospectorPropertyResolver。我写了这样的代码:

protected Property getProperty(java.lang.reflect.Type type, String expr,
                               boolean isNestedLookup, Property owner) throws MappingException {
    Property property = null;
    try {
        property = super.getProperty(type, expr, isNestedLookup, null);
    } catch (MappingException e) {
        try {
            property = super.resolveInlineProperty(type,
                    expr + ":{getInt('" + expr + "')|getInt('" + expr + "')|type=" + int.class);

        } catch (MappingException subE) {
            throw e; // throw the original exception
        }
    }
    return property;
}

这很好,Orika 自动确定 bean 上的属性名称并在 expr 中将其提供给我。但它并没有告诉我类型。它也没有告诉我我要映射到什么。我只需要假装在这种情况下目标是一个 ResultSet。

  1. 我如何知道我试图将数据放入的 expr 的类型?如果是,String我将进行内联绑定调用ResultSet.getString("expr")并告诉 Orika 使用java.lang.String. 如果是时间戳,我将进行内联绑定调用Resulset.getTimestamp("expr")并告诉 Orika 使用Timestamp
  2. 我怎么知道我正在尝试映射 from ResultSettoInternalTestPojo与例如Mapto InternalTestPojo
4

1 回答 1

1

我认为实现您要做的最简单的方法是使用自定义类映射构建器扩展默认构建器,因此您可以通过覆盖 byDefault 方法自动将字段添加到您的类映射。

这是一个使用 Orika 注释的简单示例:https ://gist.github.com/elaatifi/5212119

您不需要使用反射,您可以使用 PropertyResolver 来查找 InternalTestPojo 的所有属性,并为每个属性构建 ResultSet 的对应部分并将其添加到类映射中。

要构建对应部件属性,您可以使用 Property.Builder。属性的getter方法可以从类型中推断出来。

希望这可以帮助!

于 2015-02-27T15:53:00.560 回答