Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Spring JPA throw an error if save function is unsuccessful?

I would like to know if and what type of error is thrown by Spring JPA when trying to save an object to a database. The JpaRepository.java says to look at org.springframework.data.repository.CrudRepository#save. However, I can not seem to find what type of error is thrown, if any at all. If no error is thrown, how do I go about checking if the save was successful?

Any insight would be much appreciated.

like image 388
Eric Belfer Avatar asked Aug 12 '14 13:08

Eric Belfer


People also ask

What does save method do in JPA?

save(…)- Method. It will persist or merge the given entity using the underlying JPA EntityManager. If the entity has not been persisted yet Spring Data JPA will save the entity via a call to the entityManager.

Does Save update JPA?

You can choose between JPA's persist and merge and Hibernate's save and update methods. It seems like there are 2 pairs of 2 methods that do the same. You can use the methods persist and save to store a new entity and the methods merge and update to store the changes of a detached entity in the database.

What is the difference between save and save and flush in JPA?

On saveAndFlush , changes will be flushed to DB immediately in this command. With save , this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.


2 Answers

Spring Data Repositories throw Spring's DataAccessExceptions that are structured to allow you to catch exceptions based on certain error scenarios. E.g. a DataIntegrityViolationException is thrown to indicate foreign key violations.

The original exception is contained inside the exception being thrown so that you can get to it if you need to. By throwing a persistence technology agnostic exception, the repository clients don't get polluted with technology specific exceptions (e.g. Hibernate ones, JPA ones, MongoDB ones) so that you can exchange the repository implementation without breaking clients.

like image 65
Oliver Drotbohm Avatar answered Nov 08 '22 04:11

Oliver Drotbohm


It should throw a org.springframework.orm.jpa.JpaSystemException. Also, CrudRepostiroy.save returns you a new instance of the entity you gave it, if you get one back, that's a good sign that it saved.

like image 22
SergeyB Avatar answered Nov 08 '22 05:11

SergeyB