【问题标题】:Parent is not fetching child entities in relationships using EntityManager.find父不使用 EntityManager.find 获取关系中的子实体
【发布时间】:2023-03-03 22:18:01
【问题描述】:
@Entity
@Table(name="USR_TBL")
@Access(javax.persistence.AccessType.FIELD) 
Class UserEntity{
   @Id
   String usrIdNum

   @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name="USR_ROLE", 
         joinColumns= {@JoinColumn(name="USR_ID")}
    , inverseJoinColumns={@JoinColumn(name="ROLE_ID")}) 
    private Set<RoleEntity> roles;
}
@Entity
@Table(name="ROLE_TBL")
@Access(javax.persistence.AccessType.FIELD) 
Class RoleEntity{
     @Id
     String id
  
     String desc

}

在我的 spring 应用程序存储库类中,我写了这个

@Override
    public UserEntity findUserByUserId(String userId) {
        UserEntity userEntity = this.em.find(UserEntity.class, userId); //em is entity manager
        int size = userEntity.getRoles().size(); // how come size is 0 ??
        return userEntity;
    }

问题是不管我怎么努力,角色的大小总是0。怎么会? 请注意,我无意使用其他替代方案,例如 HQL 或标准 API。作为学习的一部分,我需要知道为什么上面的 find() 方法没有获取孩子。我什至启用了hibernate show sql,这样我就可以复制hibernate生成的sql并针对数据库执行它,是的,我在应用程序中使用的用户id确实有很多角色。

2022 年 1 月 5 日更新:
我暂时将我的查询更改为以下内容。有用!! userEntity 的角色大小为 8

UserEntity userEntity = this.em.createQuery("from UserEntity where id = 'MyAdmin1'", UserEntity.class).getResultList().get(0);

但是当我变回下面的时候

UserEntity userEntity = this.em.find(UserEntity.class, "MyAdmin1");

角色再次变为空(不为空)。
我无法结束我的问题,因为我仍然需要找到 this.em.find 无法按预期工作的根本原因。

2022 年 1 月 6 日更新:
即使我尝试使用 EntityGraph(如互联网上的建议)方法,@OneToMany 也会出现此问题。

2022 年 1 月 9 日更新:
我在 findById (由 CrudRepository 继承)上尝试以下注释:

这不行

@EntityGraph(attributePaths = ....)
public Optional<UserEntity> findById(String userId); 

这是有效的。请注意,我已经在 query.properties 上定义了相关查询

    @Query
    public Optional<UserEntity> findById(@Param("userId") String userId);

可能有人认为@EntityGraph(attributePaths = ....) 输入错误。我对此表示怀疑,因为当我在 findAll(继承自 JpaSpecificationExecutor)上尝试完全相同时,它可以工作

@EntityGraph(attributePaths = ....)
public Page<UserEntity> findAll(Specification<UserEntity> spec, Pageable pageable);

现在我想知道@EntityGraph 是否仅适用于 JPA 相关方法,但不适用于 CrudRepository 中的方法

【问题讨论】:

  • "How hard I try" 你试过插入数据吗? (否则size=0 是合乎逻辑的......如何?请展示!;)
  • 您好,感谢您的回复。数据已经在表中。而且如上所述,我什至使用hiberate生成的sql,并针对数据库执行,结果确实显示了特定用户的许多角色。但不幸的是,因为这个数据库包含我的公司数据,因此我无法显示在网络上。
  • 顺便说一句,db中的所有数据都是通过sql脚本插入的。
  • 因为我使用 Set,互联网建议覆盖 RoleEntity.. 的 hashCode 和 equals 方法。但仍然大小为 0
  • 我再次更新了我的问题以反映新的观察结果。

标签: hibernate fetch find relationship children


【解决方案1】:

我找到了原因。

  1. 我使用 findById(继承自 Crud Repository),这是不正确的。我应该编写自己的自定义查询方法,即 findByUsridNum,因为实体字段名称是 usridNum,而不是 id。现在一切正常。

  2. 有趣的是,当我使用 findById 时,我注意到 Spring Boot 框架并没有给我报错……而是继续检索记录。唯一的问题是它不再获取它的孩子,无论我做什么(使用 EAGER 获取、使用 EntityGraph 等......)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2016-04-06
    相关资源
    最近更新 更多