java 如果保存功能不成功,Spring JPA 是否会抛出错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25266248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Spring JPA throw an error if save function is unsuccessful?
提问by Eric Belfer
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?
我想知道在尝试将对象保存到数据库时 Spring JPA 是否抛出以及抛出什么类型的错误。JpaRepository.java 说要查看 org.springframework.data.repository.CrudRepository#save。但是,我似乎无法找到抛出什么类型的错误(如果有的话)。如果没有抛出错误,我该如何检查保存是否成功?
Any insight would be much appreciated.
任何见解将不胜感激。
回答by Oliver Drotbohm
Spring Data Repositories throw Spring's DataAccessException
s 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.
Spring Data Repositories 抛出 Spring 的DataAccessException
s,其结构允许您根据某些错误场景捕获异常。例如DataIntegrityViolationException
,抛出 a 以指示外键违规。
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.
原始异常包含在抛出的异常中,以便您可以在需要时访问它。通过抛出与持久性技术无关的异常,存储库客户端不会受到技术特定异常(例如 Hibernate 异常、JPA 异常、MongoDB 异常)的污染,因此您可以在不破坏客户端的情况下交换存储库实现。
回答by SergeyB
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.
它应该抛出一个org.springframework.orm.jpa.JpaSystemException
. 此外,CrudRepostiroy.save
返回给你的实体的一个新实例,如果你得到一个,那就是它保存的好兆头。
回答by prashant thakre
CrudRepostiroy.save
have return type the saved entity
CrudRepostiroy.save
有返回类型 the saved entity
<S extends T> S save(S entity)
Saves a given entity. Use the returned instance for further operations as the save operation might have changed the entity instance completely.
Parameters:
entity -
Returns:
the saved entity