2

以下のような「UserRoleHolder」というモデルがあります。

@Entity
public class UserRoleHolder extends Model implements RoleHolder {
    private static final long serialVersionUID = 1L;

    @EmbeddedId
    public UserRoleHolderPK userRoleHolderPK;
    public List<UserPermission> permissions;
    public List<UserRole> roles;
    ....

UserRoleHolderPK という複合 PK を作成しました。これには、以下のような 2 つの外部キーが含まれています。

@Embeddable
public class UserRoleHolderPK {
    @Basic
    public Long userId;
    @Basic
    public Long projectId;

    public UserRoleHolderPK(Long userId, Long projectId) {
        this.userId = userId;
        this.projectId = projectId;
    }

    public boolean equals(Object object) {
        if (object instanceof UserRoleHolderPK) {
            UserRoleHolderPK userRoleHolderPK = (UserRoleHolderPK) object;
            return userId == userRoleHolderPK.userId && projectId == userRoleHolderPK.projectId;
        } else {
            return false;
        }
    }

    public int hashCode() {
        return (int) (userId + projectId);
    }
}

userId と projectId は他のモデルのものです。(User.java と Project.java) 次に、「UserRoleHolder」クラスに、以下のような「findRolesById」というメソッドを作成しました。

public static List<? extends Role> findRolesById(Long userId, Long projectId) {
    return find
            .where()
            .eq("userRoleHolderPK", new UserRoleHolderPK(userId, projectId))
            .findUnique().roles;
}

しかし、以下のようなテスト コードを実行しようとすると、重大なエラーが発生しました。

@Test
public void findRolesById() {
    // Given
    // When
    @SuppressWarnings("unchecked")
    List<UserRole> list = (List<UserRole>) UserRoleHolder.findRolesById(1l, 1l);
    // Then
    assertThat(list.get(0).name).isEqualTo("manager");
}

エラーは次のようなものです。

'SQL 文の構文エラー "SELECT T0.USER_ID C0, T0.PROJECT_ID C1 FROM USER_ROLE_HOLDER T0 WHERE T0.NULL[*] = ? "; 期待される「識別子」; SQL ステートメント: user_role_holder t0 から t0.user_id c0、t0.project_id c1 を選択します。ここで、t0.null = ? [42001-158] バインド値:[null] クエリ: select t0.user_id c0, t0.project_id c1 from user_role_holder t0 where t0.null = ?

JPA を使用していたときに、重大で基本的なことを見逃していたと思います。何が問題なのか教えてください。

4

1 に答える 1

1

I think your problem is that you are trying to compare the Embeddedid object and not its fields, I don't think that the program will be smart enough as to know how to convert an user object comparison (the equals) to sql, so you might want to try something like this:

public static List<? extends Role> findRolesById(Long userId, Long projectId) {
    return find
            .where()
            .eq("userRoleHolderPK.userId", userId)
            .eq("userRoleHolderPK.projectId", projectId)
            .findUnique().roles;
}
于 2012-09-08T05:20:36.993 に答える