QueryBuider获取Dao.queryRaw的参数

时间:2013-04-26 13:54:58

标签: ormlite query-builder

我正在使用QueryBuider创建原始查询,但我需要手动将参数填充到原始查询。

从'和'到'的属性'被填充两次。一个在QueryBuider的'where'部分,一个在queryRaw方法中作为参数。 方法StatementBuilder.prepareStatementString()返回带有“?”的查询字符串替代。

有没有办法直接从QueryBuider实例获取这些参数?

例如,想象一下ormlite中的一个新方法 - StatementBuilder.getPreparedStatementParameters();

QueryBuilder<AccountableItemEntity, Long> accountableItemQb = accountableItemDao.queryBuilder();

QueryBuilder<AccountingEntryEntity, Long> accountingEntryQb = accountingEntryDao.queryBuilder();
accountingEntryQb.where().eq(
    AccountingEntryEntity.ACCOUNTING_ENTRY_STATE_FIELD_NAME, 
    AccountingEntryStateEnum.CREATED);
accountingEntryQb.join(accountableItemQb);

QueryBuilder<AccountingTransactionEntity, Long> accountingTransactionQb =
    accountingTransactionDao.queryBuilder();
accountingTransactionQb.selectRaw("ACCOUNTINGENTRYENTITY.TITLE, " +
        "ACCOUNTINGENTRYENTITY.ACCOUNTABLE_ITEM_ID, " +
        "SUM(ACCOUNTINGENTRYENTITY.COUNT), " +
        "SUM(ACCOUNTINGENTRYENTITY.COUNT * CONVERT(ACCOUNTINGENTRYENTITY.PRICEAMOUNT,DECIMAL(20, 2)))");
accountingTransactionQb.join(accountingEntryQb);
accountingTransactionQb.where().eq(
        AccountingTransactionEntity.ACCOUNTING_TRANSACTION_STATE_FIELD_NAME,
        AccountingTransactionStateEnum.PRINTED)
    .and().between(AccountingTransactionEntity.CREATE_TIME_FIELD_NAME, from, to);
accountingTransactionQb.groupByRaw(
    "ACCOUNTINGENTRYENTITY.ACCOUNTABLE_ITEM_ID, ACCOUNTINGENTRYENTITY.TITLE");

String query = accountingTransactionQb.prepareStatementString();

accountingTransactionQb.prepare().getStatement();

Timestamp fromTimestamp = new Timestamp(from.getTime());
Timestamp toTimestamp = new Timestamp(to.getTime());

//TODO: get parameters from accountingTransactionQb
GenericRawResults<Object[]> genericRawResults =
    accountingEntryDao.queryRaw(query, new DataType[] { DataType.STRING,
        DataType.LONG, DataType.LONG, DataType.BIG_DECIMAL },
        fromTimestamp.toString(), toTimestamp.toString());

1 个答案:

答案 0 :(得分:0)

  

有没有办法直接从QueryBuider实例获取这些参数?

是的,有办法。您需要继承QueryBuilder,然后才能使用appendStatementString(...)方法。您提供argList,然后可以使用它来获取参数列表。

protected void appendStatementString(StringBuilder sb,
        List<ArgumentHolder> argList) throws SQLException {
    appendStatementStart(sb, argList);
    appendWhereStatement(sb, argList, true);
    appendStatementEnd(sb, argList);
}
  

例如,想象一下ormlite中的一个新方法 - StatementBuilder.getPreparedStatementParameters();

好主意。我已经将following changes发给了Github回购。

public StatementInfo prepareStatementInfo() throws SQLException {
    List<ArgumentHolder> argList = new ArrayList<ArgumentHolder>();
    String statement = buildStatementString(argList);
    return new StatementInfo(statement, argList);
}
...
public static class StatementInfo {
    private final String statement;
    private final List<ArgumentHolder> argList;
    ...

该功能将在4.46版本中。如果您不想等待该版本,可以从当前主干创建一个版本。