基于Spring Boot使用JpaRepository删除数据时的注意事项

作者:石头成说 时间:2023-04-03 09:05:39 

问题:

在Spring Boot中使用JpaRepository的deleteById(ID id)方法删除数据时,首先要使用existsById(ID id)方法判断数据是否存在。如果存在,再删除。

否则,删除一个id不存在的数据会抛出org.springframework.dao.EmptyResultDataAccessException异常:


2019-01-02 15:57:24.122 WARN  org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration Line:234 - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-01-02 15:57:24.673 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] Line:175 - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.EmptyResultDataAccessException: No class com.qiqi.model.entity.UserBean entity with id 33 exists!] with root cause
org.springframework.dao.EmptyResultDataAccessException: No class com.qiqi.model.entity.UserBean entity with id 33 exists!
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.lambda$deleteById$0(SimpleJpaRepository.java:150)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository$$Lambda$798/1206249587.get(Unknown Source)
at java.util.Optional.orElseThrow(Optional.java:290)
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.deleteById(SimpleJpaRepository.java:149)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359)
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor$$Lambda$787/1363172555.get(Unknown Source)
at org.springframework.data.repository.util.QueryExecutionConverters$$Lambda$786/1029051888.apply(Unknown Source)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)

在使用其他方法时,例如:deleteAllByName(name),不进行判断也可以删除,不会抛出异常。

springboot的jpa数据库操作的坑

前一段用springboot写了篇 springboot整合多数据源小博文,从三个数据库里面抓取合适的数据。存在另外一个数据库里面。在客户生产环境运行了一段时间,感觉似乎很良好。

客户觉得意犹未尽,又提了点需求,顺便提了点bug,于是乎又改了改代码。客户居然提出一个问题,说有时候查不出数据来,过一会又好了,我在本地试了试,发现在本地竟然也存在这个问题。问题其实一直都有,只是似乎不影响什么,所以便没当一回事。

经过反复测试,原来是往数据库写数据的时候卡住了,有点奇怪。大概过程是先把表里面数据清除,然后再写入,数据不到1000条,居然耗时差不多10秒,什么springboot,什么jpa太不靠谱了吧?

看代码 ,Repository


package net.springboot.repository.sqlserver;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import net.springboot.entity.sqlserver.RealData;
public interface XXDataRepository extends JpaRepository<XXData, String>
{
}

调用代码也是简单明了


db.deleteAll();
db.saveAll(list);   //组合list这里就不写了

其实说白了,没有自己的代码,都是springboot + jpa 框架实现的,框架难道有问题,这个一般不会吧。把SQL放出来看看。

基于Spring Boot使用JpaRepository删除数据时的注意事项

基于Spring Boot使用JpaRepository删除数据时的注意事项

原来这个样子,删除全表数据,居然是一条一条数据删除,批量保存居然是先查询一下,然后再插入,JPA难道不考虑效率的吗?

问题找到了,怎么解决了?删除功能好办,自己写SQL嘛,简单方便,翠花上川菜,代码拿来。


@Transactional
@Modifying
@Query(value = "TRUNCATE TABLE table",nativeQuery = true)
int TruncateTable();
@Transactional
@Modifying
@Query(value = "delete from table",nativeQuery = true)
int deleteTable();

效果是立竿见影,删除效率上来了。清空表里数据一秒不到。不过,后来又仔细看了一下,jpa似乎还提供了另外一个删除全部数据的方法 deleteAllInBatch,这个方法在删除前似乎没有查询,懒得做测试了,习惯了自己写SQL解决问题。

但是批量插入这个不好办了,总不可能自己写成一条一条插入啊,那还不如不改了。百度一下,网上说改一下配置文件即可。


spring.jpa.properties.hibernate.jdbc.batch_size=500
spring.jpa.properties.hibernate.jdbc.batch_versioned_data=true
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true

但是好像效果不行,show sql 还是一样,先查询后插入,效率依然不行。想了很多,百度了很多,为什么了,为什么啊?JPA这玩意为什么会在插入前查询一下了,查询又是怎么个查询方式了?这个应该与主键ID有关系。所以改一下实体类,id统一为uuid模式。


   @Id
   @GenericGenerator(name = "id-generator", strategy = "uuid")
   @GeneratedValue(generator = "id-generator")
   @Column(name = "pid")
   public String pid;

效果明显,问题立马解决。但是有的系统主键ID是生成好的,有自己的规则,不可以随便uuid,比如我这个系统就是,都是在各个系统里面已经生成好了,而且还因为业务需要不能改。

没办法只有另加一个字段做为@id 虽然没啥实际意义,但是批量写入数据的问题得到彻底解决,你好,我好,大家好。

不过话说回来,插入前查询一下,这个功能是可以有,在大多数的业务场景也是很有用的。springboot的jpa就这样,在系统中,具体怎么用,码农们各显神通。

也算是趟过 springboot,jpa框架的两个坑。

来源:https://blog.csdn.net/qq_27127145/article/details/85620668

标签:Spring,Boot,JpaRepository
0
投稿

猜你喜欢

  • Java并发编程之浅谈ReentrantLock

    2022-08-25 10:46:02
  • Java数组队列概念与用法实例分析

    2023-11-18 04:18:31
  • Android中Parcelable的作用实例解析

    2022-08-07 09:19:32
  • Android全屏设置的方法总结

    2021-07-11 04:09:35
  • IDEA下Maven的pom文件导入依赖出现Auto build completed with errors的问题

    2023-04-06 07:23:31
  • C语言实例梳理讲解常用关键字的用法

    2023-04-09 01:22:52
  • C#微信开发之微信公众号标签管理功能

    2023-04-17 20:20:44
  • c# 制作gif的四种方法

    2023-03-17 20:01:08
  • SpringBoot雪花算法主键ID传到前端后精度丢失问题的解决

    2022-07-18 02:30:47
  • 流读取导致StringBuilder.toString()乱码的问题及解决

    2022-12-20 13:34:14
  • Android自定义图片集合

    2022-06-24 11:34:52
  • 利用C#代码实现图片旋转360度

    2022-04-11 05:24:38
  • c#日期间隔计算示例

    2022-11-28 07:49:48
  • Java JDK动态代理实现原理实例解析

    2022-04-23 05:19:10
  • springboot 实战:异常与重定向问题

    2022-03-06 15:44:54
  • Java JDK 二分法 分析demo(推荐)

    2022-02-28 23:29:21
  • 关于自定义过滤器获取不到session问题

    2022-05-16 11:30:21
  • Windows10 Java环境变量配置过程图解

    2022-12-16 15:08:38
  • android开发权限询问的示例代码

    2021-07-29 00:16:26
  • Android图片裁剪功能实现代码

    2021-06-13 11:03:14
  • asp之家 软件编程 m.aspxhome.com