Jpa列表查询@OneToOne,@OneToMany出现多条sql(N+1)解决办法

最近用了jpa的@OneToOne,@OneToMany管理对象,但是在查询分页列表,列表的过程中触发了N+1的sql查询,这里我用了@NamedEntityGraphs去解决

实体关系

1.父实体

/**
 * 规则配置
 *
 * @author lyj
 * @date 2023-07-06
 */
@Getter
@Setter
@Entity
@Table(name = "ca_rule_config")
@ToString(callSuper = true)
public class CaRuleConfig extends BaseEntity {
    private static final long serialVersionUID = -1799291883844292900L;

    /**
     * 课程规则配置
     */
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "schedule_id")
    private CaCourseScheduleRule caCourseScheduleRule;

}

2.子实体

/**
 * 课程排布规则
 *
 * @author lyj
 * @date 2023-07-06
 */
@Setter
@Getter
@Entity
@Table(name = "ca_course_schedule_rule")
public class CaCourseScheduleRule extends BaseEntity {
    private static final long serialVersionUID = -1523817727837148111L;

    @Fetch(value = FetchMode.SUBSELECT)
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "caCourseScheduleRule", orphanRemoval = true)
    private Set<CaTimeRuleTable> caTimeRuleTableSet;

    @JsonIgnore
    @OneToOne(fetch = FetchType.LAZY)
    @ToString.Exclude
    private CaRuleConfig caRuleConfig;
}

3.孙实体

/**
 * 规则明细表
 *
 * @author lyj
 * @date 2023-07-06
 */
@Entity
@Getter
@Setter
@Table(name = "ca_time_rule_table")
public class CaTimeRuleTable extends BaseEntity {
    private static final long serialVersionUID = 3301950476260363705L;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "schedule_id")
    @ToString.Exclude
    private CaCourseScheduleRule caCourseScheduleRule;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        CaTimeRuleTable that = (CaTimeRuleTable) o;
        return getId().equals(that.getId());
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.getId());
    }
    
}

查询语句

/**
 * @author lyj
 * @date 2023-07-06
 */
public interface CaRuleConfigDao extends BaseDao<CaRuleConfig, Long> {

    /**
     * 分页获取规则列表
     * @param spec 查询条件
     * @param pageable  分页条件
     */
    @Override
    Page<CaRuleConfig> findAll(Specification<CaRuleConfig> spec, Pageable pageable);
}

查询结果:
在这里插入图片描述
从控制台的输出我们可以看见,当前查了多少条数据就执行了多少条sql

在父实体中加入@NamedEntityGraphs后

/**
 * 规则配置
 *
 * @author lyj
 * @date 2023-07-06
 */
@Getter
@Setter
@Entity
@Table(name = "ca_rule_config")
@ToString(callSuper = true)
@NamedEntityGraphs(value = {
        @NamedEntityGraph(
                name = "caRuleConfig",
                attributeNodes = {
                        @NamedAttributeNode(value = "caCourseScheduleRule", subgraph = "caCourseScheduleRule"),
                },
                subgraphs = {
                        @NamedSubgraph(name = "caCourseScheduleRule", attributeNodes = {
                                @NamedAttributeNode(value = "caTimeRuleTableSet", subgraph = "caTimeRuleTable")
                        }),
                        @NamedSubgraph(name = "caTimeRuleTable", attributeNodes = {})
                }
        )
})
public class CaRuleConfig extends BaseEntity {
    private static final long serialVersionUID = -1799291883844292900L;

    /**
     * 课程规则配置
     */
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "schedule_id")
    private CaCourseScheduleRule caCourseScheduleRule;

}

查询接口调整

/**
 * @author lyj
 * @date 2023-07-06
 */
public interface CaRuleConfigDao extends BaseDao<CaRuleConfig, Long> {

    /**
     * 分页获取规则列表
     * @param spec 查询条件
     * @param pageable  分页条件
     */
    @Override
    @EntityGraph(value = "caRuleConfig")
    Page<CaRuleConfig> findAll(Specification<CaRuleConfig> spec, Pageable pageable);
}

执行结果
在这里插入图片描述
调用查询列表接口后,只执行了一条sql

总结:
利用@NamedEntityGraphs查询,实际就是把三张表的数据构建成一张虚拟表进行数据查询

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
我能理解你的问题,您想知道如何在JPA 2.2.10 SQL查询中使用Dto @OneToMany。在JPA中,@OneToMany关系表示一个实体具有多个子实体。Dto(Data Transfer Object)用于在不同层之间传输数据。要在SQL查询中使用Dto @OneToMany,请遵循以下步骤: 1. 创建Dto类和其对应的子Dto类。 2. 在Dto类中使用@OneToMany注释来指定实体类和关联属性。 3. 在SQL查询中使用JOIN语句来连接Dto和相关的实体类。 4. 通过使用GROUP BY子句和构造函数表达式将结果转换为Dto对象。 下面是一个示例: ``` @Entity public class ParentEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private List<ChildEntity> children; // getters and setters } @Entity public class ChildEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @ManyToOne(fetch = FetchType.LAZY) private ParentEntity parent; // getters and setters } public class ParentDto { private Long id; private String name; private List<ChildDto> children; public ParentDto(Long id, String name, List<ChildDto> children) { this.id = id; this.name = name; this.children = children; } // getters and setters } public class ChildDto { private Long id; private String name; public ChildDto(Long id, String name) { this.id = id; this.name = name; } // getters and setters } String sql = "SELECT p.id, p.name, c.id, c.name FROM ParentEntity p JOIN p.children c"; List<Object[]> resultList = entityManager.createQuery(sql).getResultList(); Map<Long, ParentDto> parentMap = new HashMap<>(); for (Object[] result : resultList) { Long parentId = (Long) result[0]; String parentName = (String) result[1]; Long childId = (Long) result[2]; String childName = (String) result[3]; ParentDto parent = parentMap.get(parentId); if (parent == null) { parent = new ParentDto(parentId, parentName, new ArrayList<>()); parentMap.put(parentId, parent); } parent.getChildren().add(new ChildDto(childId, childName)); } List<ParentDto> parentDtos = new ArrayList<>(parentMap.values()); ``` 希望这能回答您的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值