Get original object property stored in DB with Hibernate in same transaction - spring

I opened hibernate transaction and read the object. I changed some properties of object without store. I want to get the original properties stored in DB but with
Criteria cr = new Criteria(...);
cr.add(Restrictions.eq("id", id));
cr.setProjection(Projections.property("someProperty"));
cr.uniqueResult();
or reload whole object with getSession().get(id). But as a result I got changed properties and if I reload whole object I got the same instance of changed object. How to get original object properties stored in DB with same transaction, changed object must remain with changed properties.
And how to do it with Spring transaction annotations?

You can use session.refresh() method. See documentation: http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#objectstate-loading
But this will overwrite any changes. You can clone the object before refresh, i think.

Related

In a Spring Boot #Transactional Class, how to perform commits to different repositories after changes to the Hibernate DAO object in between commits?

I need to do the following in my #Transactional Class
Do changes to data (empty logs field) inside a DAO object and save to PostGresql DB
Revert the changes and save to ElasticSearch (with the id generated in the same DAO object from first commit return result).
Here is how the code is
emptylogsField(testCaseResponses); //Data modifications
Iterable<TestCaseResponse> result =
PGRepository.saveAll(converter.convertToEntities(testCaseResponses));
PGRepository.flush();
putBackLogs(result); // Data modifications
result = ESRepository.saveAll(result);
The problem is the same data is getting saved in both repositories. The flush() is not working? Please help.

REST - Fetch newly created resource without hibernate

I am using Spring MVC and NamedParameterJdbcOperations .
I am making a rest call to create an object and I want to return this newly created object.
How can then I return the newly created object regardless of the database used?
I am not using hibernate. In hibernate the persisted object can be returned immediately .But I want to achieve this without hibernate.
I used NamedParameterJdbcOperations's update method to get the key of newly created object and then fetched the object using this key.
To get the key -
GeneratedKeyHolder holder = new GeneratedKeyHolder();
namedParameterJdbcOperations.update(sql,sqlParameterSource,holder);
int key = holder.getKey().intValue();

Spring Data Neo4j Repository.save works incorrectly if it performs update

I tried to perform following actions via repository (SDN 4.0.0.RC2):
I save entity with an property with null value
I save entity again (i.e update it), but now property has a value
In this case updating is not performed. Value still is null. Is it a bug?

HibernateDAOSupport Get method

I am working on a existing project which uses Hibernate and Spring. I see a following code which uses HibernateDAOSupport class,
Employee emp = getHibernateTemplate().get(Emplyee.class, 1001)
After the above line we set some property like emp.setAge(25); and at the end we don't call any Save or SaveOrUpdate method. But it's saving the data to DB. How is it possible ?
If it can Save then what is the difference between getHibernateTemplate().get() and getHibernateTemplate().save/SaveOrUpdate methods ?
This is expected behaviour of Hibernate and it is because the Employee entity is loaded into the PersistenceContext and therefore enters the 'persistent' entity lifecycle state.
When you commit the transaction, Hibernate will check any 'persistent' entities within the PersistenceContext to see if they are "dirty". Dirty means that any values of the entity have changed. Your call to emp.setAge(25) means that Hibernate understands that data within the entity has changed (it is dirty), and it should therefore make the changes persistent when the transaction commits.
It is worth reading and understanding how Hibernate manages entity states as it can be a little confusing to start with. The documentation is here.

Double instances in database after using EntityManager.merge() in Transient Method

I am new with Spring, my application, developed with Spring Roo has a Cron that every day download some files and update a database.
The update is done, after downloading and parsing the files, using merge(),
an Entity class Dataset has a list called resources, after the download I do:
dataset.setResources(resources);
dataset.merge();
and dataset.merge() does the following:
#Transactional
public Dataset Dataset.merge() {
if (this.entityManager == null) this.entityManager = entityManager();
Dataset merged = this.entityManager.merge(this);
this.entityManager.flush();
return merged;
}
I expect that doing dataset.setResources(resources); I would overwrite the filed resources, and so even the database entry would be overwritten.
But I get double entries in the database: every resource appear twice, with different IDs (incremental).
How can I succed in let my application doing updates and not insert? A naive solution would be delete manually the old resource and then call merge(); is this the way or is there some more smart solution?
This situation occurs when you use Hibernate as persistence engine and your entities have version field.
Normally the ID field is what we need for merging a detached object with its persistent state in the database, but Hibernate takes the version field in account and if you don't set it (it is null) Hibernate discards the value of ID field and creates a new object with new ID.
To know if you are affected by this strange feature of Hibernate, set a value in the version field, if an Exception is thrown you got it. In that case the best way to solve it is the data to parse contain the right value of version. Another ways are to disable version checking (see Hibernate ref guide to know about it) or load persistent state before merging.

Resources