Java Spring Hibernate:@EntityGraph被忽略
我想使用Java Spring Hibernate:@EntityGraph被忽略,java,spring,hibernate,spring-boot,jpa,Java,Spring,Hibernate,Spring Boot,Jpa,我想使用@EntityGraph注释仅加载我需要的属性 @Entity @Data public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String username; private String pw; } public interface UserRepository extends CrudRe
@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);
}
@实体
@资料
公共类用户{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
私人长id;
私有字符串用户名;
私有字符串pw;
}
公共接口UserRepository扩展了Crudepository{
@EntityGraph(AttributePath={“用户名”})
用户readById(长id);
}
当我调用userRepository.readByid(1)时
我希望他不要加载pw属性,因为它没有在@EntityGraph
中定义,所以SQL应该是:
挑选
用户0.id作为id1\u 0\,
user0.用户名作为用户名3\u 0\u
从…起
用户user0\u
哪里
user0_u2;.id=
但Hibernate实际创建的SQL是:
挑选
用户0.id作为id1\u 0\,
用户0作为pw2,
user0.用户名作为用户名3\u 0\u
从…起
用户user0\u
哪里
user0_u2;.id=
有人能解释一下我做错了什么吗?我们需要在实体类即User.java中定义NamedEntityGraph。然后参考repo类中的entityGraph。比如说
@NamedEntityGraph({
@NamedEntityGraph(name = "User.loadUsername", attributeNodes = { @NamedAttributeNode("username") })
}
@Entity
public class User {
然后是回购类
public interface UserRepository extends CrudRepository<User, Long> {
@EntityGraph(type = EntityGraphType.LOAD, value = "User.loadUsername")
User readById(long id);
}
public interface UserRepository扩展了crudepository{
@EntityGraph(type=EntityGraphType.LOAD,value=“User.loadUsername”)
用户readById(长id);
}
您也可以在此处引用一个示例-。您链接到的文档后面紧跟着另一个示例,表明这是不必要的。username属性的类型为@Basic。在该示例中(示例77。在存储库查询方法上使用即席实体图定义),属性成员的类型为ManyToMany。这里有更多详细信息-我认为这里回答了非常相同的问题: