父实体未使用EntityManager.find获取关系中的子实体


@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
}

在我的春季应用程序存储课上,我写了这个

@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 中的方法

我找到了原因。

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

  2. 有趣的是,当我使用findById时,我注意到spring-boot框架不会给我带来错误。。。而是仍然继续检索记录。唯一的问题是,无论我做什么,它都不再获取其子级(使用EAGER获取、使用EntityGraph等…(

最新更新