I have a problem with a factory of singletons and Hibernate.
I need to have exactly one instance of objects of class MyObj for each possible value of the parameter name. So, when I execute MyObjFactory.getInstance().getMyObj("foo") (see the following code), always the same object must be returned.
I also have to persist these objects, and I was wondering how to do this.
My currently solution is the following, I'd like to know if it's correct, as I'm an Hibernate beginner and I'm not sure this is the best way to solve my problem (is it correct to persist a factory???)
I'm not sure, in particular, whether my code assures that cannot be duplicates of MyObj around (for the same parameter name) even upon object reloading
Code:
package test;
public class MyObjFactory {
private static MyObjFactory instance;
private static final Map<Integer, MyObj> generatedValues =
new HashMap<String, MyObj>();
// singleton
protected MyObjFactory() {
}
public static MyObjFactory getInstance() {
if (instance == null) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
long myId = 1; // only one instance
MyObjFactory f = (MyObjFactory) session.get(MyObjFactory.class, myId);
// if preexisting factory is found...
if (f != null) {
instance = aqf;
} else {
instance = new MyObjFactory();
session.saveOrUpdate(instance);
}
}
return instance;
}
public MyObj getMyObj(String name) {
MyObj v = generatedValues.get(name);
if (v == null) {
v = new MyObj(name);
generatedValues.put(name, v);
}
return v;
}
}
and have the class MyObj within the same package of MyObjFactory, allowing package visibility from MyObj to its factory
Code:
package test;
class MyObj {
public MyObj(String name) { ... }
}
and Hibernate code should be the following one:
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="test">
<class name="MyObjFactory">
<id name="id" column="id">
<generator class="native"/>
</id>
<map name="generatedValues" cascade="all-delete-orphan">
<key column="name"/>
<map-key column="myobj_key" type="string"/>
<one-to-many class="MyObj"/>
</map>
</class>
<class name="MyObj">
<id name="id" column="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
(some code missing, as getters/setters for id - for MyObj and MyObjFactory and name - for MyObj)