Saving an object in sleep mode using a known primary key.

My problem is with individual objects ...

I am currently using Spring with Hibernate.

I have a display object that has a primary key as a string (I know that sucks ... but code refactoring will take several months) and I want to save it. (I simplified the object with only two attributes)

@Id private String id; private String pattern; 

So, for example, I want to add something like:

["ID": "myFirstPattern", "template": "*"]

Please note that my primary key is already installed. The problem is that whenever I try to persist, Hibernate will try to associate this object with any object within the context (due to the primary key) and will not be able to do this because it is not there. Throwing an individual object error.

I did some research and came to the conclusion that merge () would satisfy my needs as it is saved and updated even if the object is not available. However, I found this a rather dirty workaround and wanted to check if there are any other solutions to this problem.

Note that we have a Helper layer, so the service level will not work directly with the HibernateDao level. Therefore, I can "mask" this by adding the "persist" and "update" methods, which will reference the same DAO merge method.

Thank you Flavio.

+7
source share
3 answers

Have you tried saveOrUpdate?

 Session sess = factory.openSession(); Transaction tx; try { tx = sess.beginTransaction(); session.saveOrUpdate( yourObjectHere ); tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { sess.close(); } 
+1
source

I tried to use some other approach after I tried the idea that Mauricio gave me. Since SaveOrUpdate used cached entities to check whether it should update or save the object, I was thinking about making things clear before saving my object.

So here is my piece of code:

 try { getHibernateTemplate().clear(); getHibernateTemplate().save(entity); } catch (DataAccessException e) { if (e.getCause() instanceof ConstraintViolationException) throw new HibernateDaoException("Entity could not be persisted. Constraint violation."); throw new HibernateDaoException(e); } 

At the moment it works as expected, although it seems that it will kill my reason for the existence of the cached database ... However, this update function will be used sparingly, since the main reason for the component is to return information, match patterns and get the best results.

In any case, I will be back soon if I find any flaws.

Any comments, please feel free to post them :)

+1
source

I'm not sure, and I canโ€™t try it right now, but doesnโ€™t set the @Id property to use the "assign" generator does this exactly?

0
source

All Articles