【问题标题】:Select multiple columns in mysql using spring data使用spring数据在mysql中选择多个列
【发布时间】:2014-11-11 07:38:42
【问题描述】:

我有下表

我的表

标识 | col1 | col2 | col3 | col4 | col5

我正在使用弹簧数据。我有以下存储库/DAO 类

public interface MyTableDAO extends JpaRepository<MyTableEntity, Integer>
{
}

我想获取一些列,比如在一个 dao 调用中我想获取 col1 和 col2,说在其他 dao 调用中我想获取 col1、col3、col5 等等......

我想要Map&lt;String, Object&gt; 中的返回数据,其中String 是列名,Object 是值。

所以我会说类似“从 id = 1 的 MyTable 中选择 col1,col2 ...(此处列表可以是任意数量的列)”,它会给我映射包含列名称作为键和值的内容。

我如何在春季数据中实现这一目标

谢谢你:)

【问题讨论】:

  • 我认为这是不可能的。在 Spring Data 中,您只能查询对象。

标签: mysql spring-data


【解决方案1】:

几个月前我在 java 中编写了一个类似的函数来进行一些数据后处理。

让我从档案中给出一个简化的版本。

protected void printResultSetAsString(ResultSet rs) throws SQLException {
    ResultSetMetaData metaData = rs.getMetaData();
    String firstLn = "";
    int columnCount = metaData.getColumnCount();
    boolean isFirstLn = true;
    String quote = "";
    if (ENCLOSEDQUOTES) {
        quote = LZConstants.ENCLOSEDCHAR;
    }
    logger.debug("Iterating result set and printing in the console ...");
    while (rs.next()) {
        Map<String, Object> columnsMap = new LinkedHashMap<String, Object>();
        for (int i = 1; i <= columnCount; i++) {
            if (isFirstLn && includeFields) {
                firstLn = firstLn + quote + metaData.getColumnLabel(i)
                        + quote + LZConstants.FIELDDELIM;
            }
            columnsMap.put(metaData.getColumnLabel(i), rs.getObject(i));
        }

        if (isFirstLn && includeFields) {
            System.out.println(firstLn);
            isFirstLn = false;
        }
        String lineCSV = LZCollectionUtils.iterateMapValuesToLine(columnsMap, quote);
        System.out.println(lineCSV);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 2017-08-31
    • 2017-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多