Spring Transactional annotation, Hibernate and persist - spring

I've a misunderstanding of Spring #Transactional annotation and persist. I am using Spring 3.1, with JPA and Hibernate. I thought that persist meant, add the entity to the persistence context (but don't execute any query until commit or flush), and that the #Transactional annotation meant, wrap the method with a transaction.
However, in this short example, when the execution pointer reaches persist, it fails with an exception, since name can't be null (db constraint).
import javax.persistence.EntityManager;
#PersistenceContext
private EntityManager entityManager;
#Transactional
public void test() {
Brand brand = new Brand();
entityManager.persist(brand);
brand.setName("test");
}
If I swap setName() and persist(), everything works. However, I don't understand why the other way around doesn't since I thought that any query would be built and executed at the end of the method.
Can someone please explain?

In JPA, once an object passed to persist() it becomes "managed", as part of becoming managed JPA implementation must generate an id for the persistent object.
If id generation is based on auto-increment (GenerationType.IDENTITY), then an insert statement needs to be issued to the db to get and assign the key. When the id generation is based on sequence / table then ids are managed and assigne by the JPA Implementation managed id pools, in which case a straight insert is not a requirement.
Having an object is passed to persist() and has become managed, any changes to it is persistent fields must be flushed to the database at the and of the transaction. In your case if the id generation is Identity then an insert must be followed an update. If the id generation is some other method then, a single insert statement is sufficient. If the transaction is rolled back, no SQL should be get sent to database at all.
This is the implementation in Batoo JPA.
Hope this makes sense.

Its committed at end of method thanks to transactional annotation. But the new record is created on persist, and any exceptions can be thrown.
Before the end of method it can still be rolled back; I normally annotate with rollback for exception.

The persist executes the "insert" query. The transacation annotation is just for starting a transaction and if a exception occurs roll back the transaction.

Related

Spring JpaRepository Perform delete only if given Id exists and avoid race condition

my situtation is as follows:
I have #Entity class Ingredient in my Spring JPA Project.
I would like to implement a method performing delete operation on DB record by record Id
public boolean deleteIngredient(String id) and if possible avoid handling exceptions for non-existent Ids.
Unfortunately the only recommendations I can find in this area are based on the fact of querying by Id before deleting record e.g.
ingredientRepository.findById(id).ifPresent(x -> ingredientRepository.deleteById(id));
or
if(ingredientRepository.existsById(id)){
ingredientRepository.deleteById(id);
}
which I believe are prone to race conditions (other thread may delete record after this one queries for existence.
Is the best approach really just wrapping it in a try-catch block and handling EmptyResultDataAccessException in case record with given Id does not exist?
If you are using JPA, you need the entity to be marked for deletion in the persistence context (e.g. not in the Database). Keep in mind JPA Repository follows the ORM paradigm and is not acting on the record directly.
Any race conditions will be handled on the persistence context level.
If you use #Transactional and you will be safe.
Also if you don't want the explicit error thrown by deleteById, when the ID is not known to the EntityManager, consider using delete (which will just return with no exception being thrown in case the ID is unknown).

Spring and Hibernate Transaction does not work for mass save operations

I am doing mass save with JpaRepository.I used #Transactional but it didn't work.I summarize the process I did:
I have two Enties
THeaderEntity
TDetailsEntity
First of all, I save the TheaderEntity because the THeaderEntity's information will be used in the TDetailsEntity (One To Many, CrudRepository.save(), 1 Header for 50 Details)
Then turn and save in the TDetailsEntity's loop.I want the entire process rollback if any registry gets an error.
#Transactional
public Result createTdetailsFromHeaderId(String token, String headerId, DetailRequests detailRequests)
I used #Transactional but only the record that received the error was rollback.
To answer why only 1 record is rolled back you might look into Spring's transactional logic - I suspect from your description that 1 transaction is opened for every save but an easy way to work on this is:
Adjust the #OneToMany relationship to cascade the persisting of entities.
Create the appropriate entities (1 THeaderEntity and 50 TDetailsEntity having all object references set correctly).
save the THeaderEntity that then should cascade the persisting to its TDetailsEntity.

How to actualize entity in Spring JPA? Actualize or create new one?

I'm wondering what is best practice to update JPA entity in Spring project - update original entity or create new? I see these two approaches:
Use original - Actualize necessary fields in original entity and save this updated entity back to the repository.
Use copy - manually create new instance of entity, set all field from original entity (+ updated fields) into new entity and save the entity back to the repository.
What approach do you use / is recommended? And why?
When it comes to updating, the standard way would be to retrieve the entity reference(read below) and make changes within a transactional method:
private JpaRepository repo;
#Transactional(readOnly = false)
public void performChanges(Integer id){
Entity e = repo.getOne(id);
// alter the entity object
}
Few things regarding the example:
You would want to use the getOne method of JpaRepository as much as possible as it is in general faster than the findOne of the CrudRepository. The only trick is that you have to be sure that entity actually exists in the database with the given id. Otherwise you would get an exception. This does not occur regarding the findOne method so you would need to make that decision regarding each transactional method which alters a single entity within your application.
You do not need to trigger any persist or save methods on the EntityManager as the changes will be automatically flushed when the transaction is commited.. and that is on method return.
Regarding your second option, I dont think thats much of a use as you would need to get the data using above method anyway. If you intend to use that entity outside of the transaction, then again you could use the one retrieved from the exmaple above and then perform merge once it is again needed within the transactional context and thus Persistence Provider.
Getting an entity and then just updating that entity is the easiest way to do that. Also this is faster than a creation of a copy since EntityManager manages an entity and know that managed entity already exists in DB (so no need to execute additional query).
Anyway, there is third and the fastest approach: using executeUpdate on Query object.
entityManager
.createQuery("update EntityName set fieldName = :fieldName where id = :id")
.setParameter("fieldName", "test")
.setParameter("id", id)
.executeUpdate();
It is faster due to bypassing the persistent context

How do I execute named queries from a JPA EntityListener?

I have a requirement to set a date_updated value in my database for each row when that row is updated. Let's call the entity that I'm working with Order, which has a corresponding orders table in the database.
I've added the date_updated column to the orders table. So far, so good.
The #Entity Order object that I'm working with is provided by a third party. I do not have the ability to modify the source code to add a field called dateUpdated. I have no requirement to map this value to the object anyway - the value is going to be used for business intelligence purposes only and does not need to be represented in the Java entity object.
My problem is this: I want to update the date_updated column in the database to the current time each time an Order object (and its corresponding database table row) is modified.
Constraints:
We are using Oracle, Spring, JPA and Hibernate
I cannot use Oracle triggers to update the value. We are using a database replication technology that prevents us from using triggers.
My approach thus far has been to use a JPA EntityListener, defined in xml, similar to this:
<entity-mappings xmlns="....">
<entity class="com.theirs.OrderImpl">
<entity-listeners>
<entity-listener class="com.mine.listener.OrderJPAListener" />
</entity-listeners>
</entity>
</entity-mappings>
My listener class looks like this:
public class OrderJPAListener {
#PostPersist
#PostUpdate
public void recordDateUpdated(Order order) {
// do the update here
}
}
The problem I'm having is injecting any sort of persistence support (or anything at all, really) into my listener. Because JPA loads the listener via its methods, I do not have access to any Spring beans in my listener class.
How do I go about injecting an EntityManager (or any Spring bean) into my listener class so that I can execute a named query to update the date_updated field?
How do I go about injecting an EntityManager (or any Spring bean) into
my listener class so that I can execute a named query to update the
date_updated field?
As noted above JPA 2.1 supports injecting managed beans to an Entity Listener via CDI. Whether or not Spring supports this I am not sure. The folloiwng post proposes a Spring specific solution.
https://guylabs.ch/2014/02/22/autowiring-pring-beans-in-hibernate-jpa-entity-listeners/
A possible alternative approach would be however to override the SQL generated by Hibernate on an update which is possible as detailed below.
https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/querysql.html#querysql-cud
This would be straightforward if you had the source as you would just need to add the #SQLUpdate annotation and tag on the additional date_update column. As you don't however you would need to look at redefining the metadata for that Entity via an xml configuration file and defining the sql-update statement as outlined above:
https://docs.jboss.org/hibernate/stable/annotations/reference/en/html/xml-overriding.html#xml-overriding-principles-entity
Since JPA 2.1 Entity Listeners are CDI managed. Have you tried using #PersistenceUnit annotation? Are you using JTA transaction type?
Otherwise you could use Persistence.createEntityManagerFactory within the Listener class to retrieve the Persistence Context.

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.

Resources