记: Spring Data Jpa @OneToMany 级联查询被动触发的问题

I have encountered a bug in using Spring Data Jpa. Specifically,when @OneToMany was used to maintain a one-to-many relationship, lazy loading was effective.However,it may passively trigger the cascading query without using the cascading property.

My development?environment :

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.11.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

My User.class is as follows

My Paper.class is as follows

My PaperService.class is as follows

My UserController.class is as follows

I would like to use Jpa‘s @OneToMany default lazy loading mechanism when pagination queries was produced. Additionally, I don‘t need the collection of papers fields associated with the user.Nevertheless,I find that the papers attribute in the user is still populated with data in the returned results.

Therefore, I conducted the following debugging:**

send a request

Observe the execution of the code:

As you can see, although the lazy loading of Jpa was normal, I found the papers values that needed to be populated by cascading queries in the response data

I guess the user‘s papers field in Page must have been used by the framework before the data was written back to the browser, so I started with the UserController and continued to trace the source code

Then I was found the following call: Jackson called paper‘s getter through reflection while serializing the data . in the package com. Fasterxml. Jackson. Databind. Ser.

That‘s why I get a response in which the paper property is populated with a value, right

Look at it this way, even though lazy loading of Jpa is in effect, cascading queries are triggered passively

Lazy loading is in effect, but the cascading query is still triggered passively, which is not the result we want, I wonder what you think about it

  • solution 1:
    @RequestMapping(path = "/getUserByPage")
    public Page getUserByPage(@RequestParam Integer from, @RequestParam Integer limit, @RequestParam(required = false) String name) {
        Page<User> page = userService.getUserByPage(from, limit, name);
        page.getContent().forEach(user->{
            user.setPapers(null);
        });
        return page;
    }
  • solution 2: @JsonIgnore

@JsonIgnore can handle this pretty well, so why not let @onetomany have it?

    @JsonIgnore
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL,fetch = FetchType.LAZY)
    private Set<Paper> papers = new HashSet<>();
  • solution 3:

We can get rid of the getters (papers), but if we do that, we can‘t use the property by ourselves

原文地址:https://www.cnblogs.com/ZhuChangwu/p/12158405.html

时间: 2024-10-10 15:46:21

记: Spring Data Jpa @OneToMany 级联查询被动触发的问题的相关文章

Spring data jpa @OneToMany 在一的一端进行查询()对集合属性设置条件查询)

业务场景: 一个商品对应多个仓存,需要查询商品在某个或某几个库存中存在时,查询出来. 实体类 ,商品Goods @Entity @Table(name = "es_goods") public class Goods { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "goods_id") private Integer id; private String name; //

Spring Data Jpa之高级查询(jpa-spec插件)

友情链接:Spring Data Jpa的动态查询库 https://github.com/wenhao/jpa-spec 功能介绍 兼容Spring Data Jpa 和JPA2.1接口. Equal/NotEqual/Like/NotLike/In/NotIn支持可变参数, Equal/NotEqual 支持空(Null)值. 每个条件支持关联查询. 支持自定义条件查询. 条件构建器. 支持分页和排序. 导包: <dependency> <groupId>com.github.

spring data jpa 一对多查询

在一对多关系中,我们习惯把一的一方称之为主表,把多的一方称之为从表.在数据库中建立一对多的关系,需要使用数据库的外键约束. 什么是外键? 指的是从表中有一列,取值参照主表的主键,这一列就是外键. package com.ytkj.entity; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @Entity * 作用:

spring data jpa的动态查询封装(转)

最近使用spring data jpa做了两个项目,对于动态查询的不友好做了个类似hibernate的封装,记录也分享下 首先定义一个所有条件的容器,继承Specification Java代码   /** * 定义一个查询条件容器 * @author lee * * @param <T> */ public class Criteria<T> implements Specification<T>{ private List<Criterion> crit

Spring data JPA 理解(默认查询 自定义查询 分页查询)及no session 两种处理方法

简介:Spring Data JPA 其实就是JDK方式的动态代理 (需要一个接口 有一大堆最上边的是Repository接口来自org.springframework.data.repository,还有CrudRepository接口及一个实现类SimpleJpaRepository),只要有接口就可以查询数据库了,实际上就是proxy的方法,具体查询的方法有两种一种是简单式就是方法名为findBy+属性名+(AndOrIsEquals等)另一种是自定义的方法就是属性名是瞎起的向abc xy

spring data jpa Specification 复杂查询+分页查询

当Repository接口继承了JpaSpecificationExecutor后,我们就可以使用如下接口进行分页查询: /** * Returns a {@link Page} of entities matching the given {@link Specification}. * * @param spec can be {@literal null}. * @param pageable must not be {@literal null}. * @return never {@l

Spring Data JPA原生SQL查询

package com.wanda.cms.dao.repository;import org.springframework.stereotype.Repository;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import java.math.BigInteger;import java.util.*; /*

jpa @onetomany 级联查询时会有重复数据,去重问题

自己是直接查出来然后利用set去重(自己感觉不是太好,不过能达到目的) List<CampaignDashboardDimensionDo> list = query.getResultList();Set<CampaignDashboardDimensionDo> set=new HashSet<>(list);如有更好的方法,希望大佬留言,谢谢 原文地址:https://www.cnblogs.com/zqr99/p/9222239.html

【Spring Data 系列学习】Spring Data JPA 自定义查询,分页,排序,条件查询

Spring Boot Jpa 默认提供 CURD 的方法等方法,在日常中往往时无法满足我们业务的要求,本章节通过自定义简单查询案例进行讲解. 快速上手 项目中的pom.xml.application.properties与 Chapter1 相同 实体类映射数据库表 user 实体类 @Entity public class User implements Serializable { private static final long serialVersionUID = -39076354