0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

pojo

Posted at

如果你的检索结果的 POJO 是动态的,即其字段是不确定的,那么你可以考虑使用 Java 反射来动态设置结果集中每个记录的值。

具体来说,你可以在 SelectProvider 中构建出一个动态的 ResultMap,然后在返回结果的时候使用 Java 反射来将每个记录的值设置到对应的 POJO 中。以下是一个示例:

public interface MyMapper<T> {
    @SelectProvider(type = MyProvider.class, method = "dynamicSQL")
    List<T> select(String tableName, String[] columns);
}

public class MyProvider {
    public String dynamicSQL(String tableName, String[] columns) {
        // 构建动态的 ResultMap
        StringBuilder resultMapBuilder = new StringBuilder("<resultMap type=\"");
        resultMapBuilder.append("com.example.DynamicPojo");
        resultMapBuilder.append("\" id=\"resultMap\">\n");

        for (String column : columns) {
            resultMapBuilder.append("<result property=\"");
            resultMapBuilder.append(column);
            resultMapBuilder.append("\" column=\"");
            resultMapBuilder.append(column);
            resultMapBuilder.append("\" />\n");
        }

        resultMapBuilder.append("</resultMap>");

        // 构建 SQL
        StringBuilder sqlBuilder = new StringBuilder("SELECT ");

        for (String column : columns) {
            sqlBuilder.append(column);
            sqlBuilder.append(",");
        }

        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        sqlBuilder.append(" FROM ");
        sqlBuilder.append(tableName);

        return "<script>" + resultMapBuilder.toString() + sqlBuilder.toString() + "</script>";
    }
}

public class DynamicPojo {
    // 使用反射来设置每个记录的值
    public void setField(String fieldName, Object value) {
        try {
            Field field = this.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(this, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

在上面的示例中,我们首先定义了一个 MyMapper 接口,其中的 select 方法使用了 SelectProvider 注解,其参数包括表名和要查询的列名数组。然后,我们定义了一个 MyProvider 类,其中的 dynamicSQL 方法根据传入的表名和列名数组构建出一个动态的 ResultMap,并拼接出相应的 SQL 语句。最后,我们定义了一个 DynamicPojo 类作为动态的 POJO,其中的 setField 方法使用 Java 反射来设置每个记录的值。

你可以根据自己的需求来修改上面的代码。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?