Custom SQL Using a Class
Select all rows with quanities of 1 to 42.
// set up
Database database = new Database(getConnection());
Table<Inventory> inventoryTable = database.getTable(Inventory.class);
// select operation for range
QuantityRangeSelect operation = new QuantityRangeSelect(inventoryTable);
operation.setRange(1, 42);
// show results
for (Inventory inventory: operation.selectAll())
{
System.out.println(inventory.getPartNumber() +
" quantity=" + inventory.getQuantity());
}
QuantityRangeSelect.java:
public class QuantityRangeSelect extends ArrayListSelectOperation<Inventory>
{
int minimumQuantity;
int maximumQuantity;
public QuantityRangeSelect(Table<Inventory> table) throws OperationException
{
super(table);
// custom sql appended to "select partnumber, quantity... from inventory"
setCustomSql("where quantity between ? and ?");
}
public void setRange(int minimumQuantity, int maximumQuantity)
{
this.minimumQuantity = minimumQuantity;
this.maximumQuantity = maximumQuantity;
}
@Override
protected void writeParameters() throws OperationException
{
try
{
// standard JDBC
PreparedStatement ps = getPreparedStatement();
ps.setInt(1, minimumQuantity);
ps.setInt(2, maximumQuantity);
}
catch (SQLException e)
{
throw new OperationException("error preparing quantity range", e);
}
}
}
INVENTORY schema and Inventory.java used by this example.
See SimpleExample.java class in the Simple Example download.
|