title: Dynamic Query in Jasper Report
body: <p>I'm using Jasper Reports with Java to create some reports. In the interface, the user selects 1 or more items, and a report is generated for each item. Now, I have the query:</p>
  
  <pre><code>SELECT * FROM StockInventory
  </code></pre>
  
  <p>This is in the jrxml file. But, running that through my app, it'll create a report for every single item in the table. What I'd like is:</p>
  
  <pre><code>SELECT * FROM StockInventory WHERE pk IN (?...)
  </code></pre>
  
  <p>Where "?..." are the keys of the items the user selects. So, not only is the parameter dynamic, but the number of parameters is also dynamic.</p>
  
  <p>My problem is, I don't know how to setup the parameters in the jrxml and I don't know how to set the parameters from within the jasperreports library in Java. Currently, to set values I'm doing this:</p>
  
  <pre><code>Map&lt;String, Object&gt; params = new HashMap&lt;String, Object&gt;();
  JasperReport report = JasperCompileManager.compileReport("path\\to\\jrxml");
  JasperPrint print = JasperFillManager.fillReport(report, params, new ItemData(keys));
  </code></pre>
  
  <p>Where ItemData() is :</p>
  
  <pre><code>private class ItemData implements JRDataSource
  {
      private final List&lt;InventoryItem&gt; items;
      private int counter;
  
      public ItemData(List&lt;PrimaryKey&gt; keys)
      {
          items = new ArrayList&lt;InventoryItem&gt;();
  
          InventoryItemDao dao = new InventoryItemDao();
          for(PrimaryKey key : keys)
          {
              InventoryItem item = dao.find(key.getPk(), key.getCpk());
              if (item != null)
              {
                  items.add(item);
              }
          }
  
          counter = -1;
      }
  
      @Override
      public boolean next() throws JRException 
      {
          if ( counter &lt; items.size() - 1)
          {
              counter++;
              return true;
          }
          return false;
      }
  
      @Override
      public Object getFieldValue(JRField jrf) throws JRException 
      {
          // Return the relevant field
      }
  }
  </code></pre>
  
  <p>The problem with this is that it's looping through the primary keys the user selected and running a query for each of those. If I could just do this with a single dynamic query, it would be much simpler.</p>
  
  <p>Thanks for any help!</p>