在JOIN期间用于子属性的Spring数据JPA @EntityGraph

时间:2018-09-02 13:23:35

标签: hibernate spring-boot spring-data-jpa

我想从子实体中查询父实体(以及EntityGraph中指定的映射实体)。

用户实体:

public class User{
    private Long userId;
    //other fields
    private Set<UserRoleOrganization> userRoleOrganizations;

    //Setters and getters
}

UserToken实体:

public class UserToken{
    private Long userTokenId;
    @OneToOne
    @JoinColumn(name = "user_id", referencedColumnName = "user_id", nullable = false)
    private User user;

    @Column(name = "user_token", length = 100, unique = true)
    @NotNull
    private String userToken;

}

我确实喜欢以下内容:

@EntityGraph(attributePaths = { "userRoleOrganizations" })
@Query("Select t.user From UserToken t Where t.userToken = :accessToken")
User findDetailedUserByUserToken(@Param("accessToken") String accessToken);

但是我遇到了如下异常:

Caused by: org.hibernate.QueryException: could not resolve property: userRoleOrganizations of: com.dao.domain.security.UserToken

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我建议您也从用户实体添加一对一关系。这样,您可以从用户端编写查询。这是更改:

1。添加另一边关系:

  • 在用户中添加UserToken实体关联船舶

    public class User{
        @OneToOne(mappedBy='user')
        private UserToken uToken;
        //other fields
        //Setters and getters
    }
    

2。重写查询:

  • 您只需要从用户端编写查询

     @EntityGraph(attributePaths = { "userRoleOrganizations" })
     @Query("Select t From User t Where t.uToken.userToken = :accessToken")
     User findDetailedUserByUserToken(@Param("accessToken") String accessToken);