首页 > 解决方案 > Spring Data JPQL 不过滤 OneToMany 关系的关联实体

问题描述

我正在处理 spring 数据并使用Spring Boot 2.1.0.RELEASE并使用 JPQL 查询关联/嵌入实体字段以@OneToMany获取关联实体类过滤器的关系,但它检索所有嵌入对象也使用fetch = FetchType.EAGER但不过滤关联对象和负载所有的对象。下面是实体和回购类。

第一个实体类

@Entity
@Table(name = "USER")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @OneToMany(mappedBy = "user", targetEntity = AuthorityEntity.class, fetch = FetchType.LAZY, cascade=CascadeType.ALL)
    private List<AuthorityEntity> authorities;

    //Setter getter
}

第二个实体类

@Entity
@Table(name = "AUTHORITY")
public class AuthorityEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String authorityType;
    private String textType;

    @JsonBackReference
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    private UserEntity user;

    //Setter getter
}

存储库接口

@Repository
public interface UserRepo extends JpaRepository<UserEntity, Long> {
    UserEntity findByUsernameAndAuthoritiesAuthorityType(String username, String authority);
}

我也尝试了 HQL @Query("select u from UserEntity u JOIN FETCH AuthorityEntity a on u.id = a.user where u.username = ?1 and a.authorityType = ?2"),但它也获取了所有子对象而不是过滤子对象。

让我知道我错在哪里,是否需要任何配置?

标签: hibernatespring-bootspring-data-jpaspring-datahibernate-mapping

解决方案


经过努力,我找到了 JPA Entity Graph 的解决方案

@NamedEntityGraph(name = "USER.AUTHORITY", attributeNodes = { @NamedAttributeNode("authorities") })
public class UserEntity 

@EntityGraph(value = "USER.AUTHORITY", type = EntityGraphType.LOAD)
UserEntity findByUsernameAndAuthoritiesAuthorityType(String username, AuthorityType authority); 

这对于 OneToMany 和过滤子对象非常有效,但在 ManyToMany 关系的情况下它也会失败。


推荐阅读