Avoiding Unexpected Comma Formatting of Large Integers with MessageFormat in MyBatis SQL Generation
When using MessageFormat to inject integer parameters into dynamically generated MyBatis SQL, large numbers are automatically formatted with commas (e.g., 10000 becomes 10,000), which can break SQL statements, and the article explains why this happens and how to prevent it by converting numbers to strings before formatting.
When building SQL statements dynamically with org.apache.ibatis.jdbc.SQL , developers often use java.text.MessageFormat to substitute parameters. This works fine for small integers, but for larger values (e.g., 10000) MessageFormat inserts a comma, producing 10,000 instead of the expected 10000 .
Example code :
import org.apache.ibatis.jdbc.SQL;
import java.text.MessageFormat;
/**
* @author 认知科技技术团队
*/
public class DemoConfig {
public static void main(String[] args) {
SQL sql = new SQL();
sql.SELECT("a,b,c");
sql.FROM("test_table");
sql.WHERE("a > {0} ");
// Using MessageFormat with an integer parameter
String sqlStr = MessageFormat.format(sql.toString(), 100);
System.out.println(sqlStr);
}
}Running the program with 100 prints the expected SQL string, but changing the parameter to 10000 results in the integer being formatted as 10,000 , which is not suitable for SQL.
The root cause is that MessageFormat.format converts all arguments to String using NumberFormat (specifically DecimalFormat ) when the argument is a numeric type. DecimalFormat applies the default locale's grouping separator, which inserts commas for thousands.
How to avoid the unwanted formatting
Convert the numeric argument to a string explicitly before passing it to MessageFormat.format . Examples:
MessageFormat.format(sql.toString(), "" + 10000);
MessageFormat.format(sql.toString(), String.valueOf(10000));
MessageFormat.format(sql.toString(), Long.toString(10000));By providing a String argument, MessageFormat skips the numeric formatting step and inserts the value unchanged.
Conclusion
Java's MessageFormat formats large integers using DecimalFormat , which adds commas according to the default locale. To prevent this behavior in dynamically generated SQL, always convert integer parameters to strings before formatting.
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.