在Spring JPA2中找不到类型错误的复合键属性

时间:2016-07-30 21:41:05

标签: spring hibernate jpa spring-data-jpa

我在春季JPA中有错误

org.springframework.data.mapping.PropertyReferenceException:找不到类型为CompanyUserDetail的属性CompanyId!

@Embeddable
public class CompanyUserKey implements Serializable {

public CompanyUserKey() {
}

@Column(name = "company_id")
private UUID companyId;

@Column(name = "user_name")
private String userName;

public UUID getCompanyId() {
    return companyId;
}

public void setCompanyId(UUID companyId) {
    this.companyId = companyId;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}
}


@Entity
@Table(name = "company_user_detail")
public class CompanyUserDetail {


@EmbeddedId
CompanyUserKey companyUserkey;

public CompanyUserKey getCompanyUserkey() {
    return companyUserkey;
}

public void setCompanyUserkey(CompanyUserKey companyUserkey) {
    this.companyUserkey = companyUserkey;
}
}

我正在尝试访问以下方法服务层

@Component
public interface CompanyUserRepository extends JpaRepository<CompanyUserDetail, CompanyUserKey> {

public List<CompanyUserDetail> findByCompanyId(UUID companyId);
}

我怎样才能做到这一点?

谢谢

2 个答案:

答案 0 :(得分:1)

由于在java模型中,CompanyUserKeyCompanyUserDetail类中的属性,我相信您应该使用完整路径(companyUserkey.companyId)来到达companyId

public List<CompanyUserDetail> findByCompanyUserkeyCompanyId(UUID companyId);

另请注意,您的命名不一致:CompanyUserDetail中的字段名为companyUserkey,而不是companyUserKey

答案 1 :(得分:0)

假设您没有使用spring-data-jpa自动生成的实现,您的方法内容可能如下所示:

FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId

现在只需将该查询提供给EntityManager

即可
entityManager.createQuery( queryString, CompanyUserDetail.class )
             .setParameter( "companyId", companyId )
             .getResultList();

关键点是:

  • Query使用名为:companyId 的命名绑定参数(不是前导:)。
  • 使用setParameter方法变体在辅助步骤中绑定参数值。
  • createQuery使用第二个参数来影响类型安全性,以便getResultList的返回值与您请求的List<CompanyUserDetail>一样。

然而,看看spring-data-jpa的实现,我怀疑它看起来像这样:

public interface CustomerUserRepository 
                 extends JpaRepository<CompanyUserDetail, CompanyUserKey> {
  @Query("select c FROM CompanyUserDetail c WHERE c.companyUserKey.companyId = :companyId")
  List<CompanyUserDetail> findByCompanyId(@Param("companyId") UUID companyId);
}