fgamito wrote:
Hibernate version:3.0.5
I need to implement a IdentifierGenerator that must be one Singleton by SessionFactory.
Anyone can explain the better way to do this ?
fmg
Assuming the goal is that you simply want to generate ids from the same pool and not that you really need a singleton (you don't have control over this since the framework is responsible for creating identifier generators), something like the following should do the trick.
Note that this is overkill for a primitive integer (you can reduce the code to literally 5 lines, but this should work if you've got a fancier generation algorithm requiring objects.
Code:
public class SharedGenerator implements IdentifierGenerator {
private static SharedGenerator singleton;
private static long id = 0;
public SharedGenerator() {
// Generators are created during mapping, so there should be no need for synchronization
if (singleton == null) {
singleton = this;
}
}
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
if (this == singleton) {
synchronized (singleton) {
return new Long(++id);
}
} else {
return singleton.generate(session, object);
}
}
}