I'm doing something really simple with my BD, and it appears to be failing. The code is below. Basically, what myMethod() does is check if certain entry on my DB matches a certain criteria, and if it doesn't, it inserts an object that matches it.
Well, I've detected that when in my application two threads go trough that point at once, it sometimes saves the object twice. Am I doing something wrong with the transaction?
Code:
public void myMethod() {
try{
sessionFactory.getCurrentSession().beginTransaction();
MyObject myObject = getSomeObjectFromDB("1234");
if (myObject == null) {
myObject = new MyObject();
myObject.setSomeParam("1234");
sessionFactory.getCurrentSession().saveOrUpdate(myObject);
}
sessionFactory.getCurrentSession().getTransaction().commit();
} catch (Throwable d) {
sessionFactory.getCurrentSession().getTransaction().rollback();
}
}
public MyObject getSomeObjectFromDB(String param){
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(MyObject.class);
criteria.add(Expression.eq("someParam", param));
return criteria.list().isEmpty() ? null : (MyObject)criteria.list().get(0);
}