【问题标题】:Spring Hibernate: @EntityGraph is ignoredSpring Hibernate:@EntityGraph 被忽略
【发布时间】:2020-03-12 11:14:50
【问题描述】:

我想使用@EntityGraph注解只加载我需要的属性。

@Entity
@Data
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    private String username;
    private String pw;

}

public interface UserRepository extends CrudRepository<User, Long> {

    @EntityGraph(attributePaths = {"username"})
    User readById(long id);

}

当我调用userRepository.readByid(1);时,我希望他不会加载pw属性,因为它没有在@EntityGraph中定义,所以SQL应该是:

选择 user0_.id 为 id1_0_, user0_.用户名作为用户名3_0_ 从 用户user0_ 在哪里 user0_.id=?

但 Hibernate 实际创建的 SQL 是:

选择 user0_.id 为 id1_0_, user0_.pw 作为 pw2_0_, user0_.用户名作为用户名3_0_ 从 用户user0_ 在哪里 user0_.id=?

谁能解释一下我做错了什么?

【问题讨论】:

标签: java spring hibernate spring-boot jpa


【解决方案1】:

我们需要在Entity类即User.java中定义NamedEntityGraph。然后在 repo 类中引用 entityGraph。例如

    @NamedEntityGraph({
        @NamedEntityGraph(name = "User.loadUsername", attributeNodes = { @NamedAttributeNode("username") })
    }
@Entity
public class User {

然后在 repo 类中

public interface UserRepository extends CrudRepository<User, Long> {

    @EntityGraph(type = EntityGraphType.LOAD, value = "User.loadUsername")
    User readById(long id);

}

您也可以在此处参考示例 - https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-graph

【讨论】:

  • 您链接到的文档在您链接到的文档之后有另一个示例,表明这不是必需的。
  • 用户名属性是@Basic 类型。在该示例中(示例 77。在存储库查询方法上使用 AD-HOC 实体图定义)属性成员的类型为 ManyToMany。
  • 更多细节在这里 - stackoverflow.com/a/53906287/1358551
猜你喜欢
  • 2018-02-25
  • 2023-03-21
  • 2013-04-24
  • 2020-01-04
  • 2014-04-28
  • 2020-05-07
  • 2018-07-26
  • 1970-01-01
  • 2017-12-05
相关资源
最近更新 更多