I have some code/application which uses Hibernate 3.
It does calls like:
query.setParameter("MRC", getPageName(), new StringType());
query.setParameter("MBID", getMBID(), new IntegerType());
I want to replace these calls with some code like:
query.setParameter("MRC", getPageName(), STRING_TYPE);
query.setParameter("MBID", getMBID(), INTEGER_TYPE);
so that I don't have to instantiate these objects (the 3rd parameters) each time.
Here STRING_TYPE and INTEGER_TYPE will be static private class variables
of types StringType and IntegerType respectively.
I wonder if that's safe to do (e.g. from multi-threading perspective, or purely from object reuse perspective).
I noticed that in later versions of Hibernate they imposed using the 2nd way of coding, but I am not sure if it's safe to follow this newer pattern in Hibernate 3 too.
Any ideas?
The StringType has <edited>no</edited> member fields and therefore no state itself. In the source code, all operations are either performed directly on the parameters or deal with singleton objects. That means that reusing a singleton instance is just as safe as creating a new instance each time. However, since the singleton instances are also immutable objects (a string constanct, String.class, or a static final int), then both variations should be considered safe.
Here is the source code.