hibernate - 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")
,但它也获取了所有子对象而不是过滤子对象。
让我知道我错在哪里,是否需要任何配置?
解决方案
经过努力,我找到了 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 关系的情况下它也会失败。
推荐阅读
- c# - 如何从列表中删除特定的游戏对象(在数组中)?
- python - 实现的基类方法中的Python抽象方法
- c++ - 当我有多态指针时使用“零规则”
- javascript - 如何从一个特定对象返回值?
- r - 从子集数据框创建新数据框
- google-apps-script - Google Apps 脚本中的缓存是否有限制?
- java - 安装插件后无法使用依赖项 Spring-boot 打包 jar
- c# - 数据表未加载说等待激活json
- javascript - How can I compare a string A1 with a value A2 (index 0's) in and array values?
- python - 如何通过xpath从scrapy的源代码中提取部分?