* @param template The product to sell
* @return Whether the product was sold
*/
public static boolean sellOneProduct(Product template)
{
PersistenceBroker broker = null;
boolean isSold = false;
try
{
broker = PersistenceBrokerFactory.defaultPersistenceBroker();
QueryByCriteria query = new QueryByCriteria(template);
Product result = (Product)broker.getObjectByQuery(query);
if (result != null)
{
broker.beginTransaction();
result.setStock(result.getStock() - 1);
broker.store(result);
// alternative, more performant:
// broker.store(result, ObjectModificationDefaultImpl.UPDATE);
broker.commitTransaction();
isSold = true;
}
}
catch (PersistenceBrokerException ex)
{
if (broker != null)
{
broker.abortTransaction();
}
ex.printStackTrace();
}
finally
{
if (broker != null)
{
broker.close();
}
}
return isSold;
}