Reputation: 183
I'm not sure my use of the Random class is right--perhaps I am misinterpreting it. (I've seen this usage many times, however, in my Googles.)
I'm trying to generate unique invoice numbers by concatenating a random number and a string, looking up that invoice in the database to see if it exists, and if it does then create a new invoice number and try again. Following is my code, and below that the method used to test the truthfulness of the while clause:
String iname = "foo";
int sequence = 0;
String invoice_name = "";
Random generator = new Random();
do {
sequence = generator.nextInt( 1000 );
invoice_name = iname + String.format("%03d", sequence);
} while( !isUniqueInvoiceName( invoice_name, params, qb )
// QueryBatch is just a caching mechanism and batch committer for queries
private boolean isUniqueInvoiceName(String invoice_name, HashMap params, QueryBatch qb) {
if( params.get("x_invoice_num") == null ) params.put( "x_invoice_num",invoice_name );
// Invoice.select returns the primary key of the top 1 invoices found, or 0 if none found.
int pk = Invoice.select(params, qb);
System.out.println("============= pk = " + pk + " =============");
return ( pk == 0 );
}
What happens is that the error log shows pk = 13 (or something) and then it repeats that message infinitely. I can't see why. Is a new random number not being generated? Or is the only explanation that the select method is returning the same results without looking at the new parameters? Maybe a caching issue? This is on tomcat/MS SQL.
Upvotes: 0
Views: 1167
Reputation: 8147
i think the problem is with this line:
if( params.get("x_invoice_num") == null ) params.put( "x_invoice_num",invoice_name );
after the first time you set the x_invoice_num
value it will never be null again so it will never update.
i think you don't want the put()
to be conditional at all.
Upvotes: 2