Created
December 30, 2014 20:57
-
-
Save maxant/3b2faaeca920843c515b to your computer and use it in GitHub Desktop.
Asynchronous persistence
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void persistSales(List<Sale> sales, final PersistenceComplete f) { | |
if (!sales.isEmpty()) { | |
LOGGER.info("preparing to persist sales"); | |
final AtomicInteger count = new AtomicInteger(sales.size()); | |
sales.forEach(sale -> { | |
List values = Arrays.asList(sale.getBuyer().getName(), | |
sale.getSeller().getName(), | |
sale.getProductId(), | |
sale.getPrice(), | |
sale.getQuantity(), | |
sale.getPurchaseOrder().getId(), | |
sale.getSalesOrder().getId()); | |
Future<QueryResult> sendQuery = POOL.sendPreparedStatement(SQL, JavaConversions.asScalaBuffer(values)); | |
sendQuery.onComplete(new JFunction1<Try<QueryResult>, Void>() { | |
@Override | |
public Void apply(Try<QueryResult> t) { | |
if(t.isSuccess()){ | |
QueryResult qr = t.get(); | |
//the query result doesnt contain auto generated IDs! library seems immature... | |
//sale.setId(???); | |
} | |
if(count.decrementAndGet() == 0){ | |
if(t.isSuccess()){ | |
f.apply(null); | |
}else{ | |
f.apply(t.failed().get()); | |
} | |
} | |
return null; //coz of Void | |
} | |
}, Main.system.dispatcher()); | |
}); | |
}else{ | |
f.apply(null); //nothing to do, so continue immediately | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment