如何在JPA中选择和订购EmbeddedID

时间:2013-12-31 10:45:29

标签: java hibernate jpa

我有一个包含复合主键的表:

public class IdmTenantBoard implements Serializable {
private static final long serialVersionUID = 1L;

@EmbeddedId
private IdmTenantBoardPK id;

@Column(name="board_display_name")
private String boardDisplayName;

@Column(name="board_name")
private String boardName;

嵌入式类看起来像这样:

public class IdmTenantBoardPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;

@Column(name="board_id")
private int boardId;

@Column(name="tenant_id")
private String tenantId;

我用来调用查询的方法如下:

public String getMaxBoardId(){
      TypedQuery<String> query = entityManager.createQuery("select o from IdmTenantBoard o order by o.IdmTenantBoardPK.boardId desc",String.class);
      query.setMaxResults(1);
      List<String> lResults = query.getResultList();
      String maxBoardId=null;
      if((null!=lResults)&&(!lResults.isEmpty())){
          maxBoardId=lResults.get(0);
      }
      return maxBoardId;
}

如何按降序排序boardId需要什么?我收到以下错误:

  

引起:org.hibernate.QueryException:无法解析属性:IdmTenantBoardPK:com.newrubric.idm.common.entities.IdmTenantBoard [select from com.newrubric.idm.common.entities.IdmTenantBoard o order by o .IdmTenantBoardPK.boardId desc]

4 个答案:

答案 0 :(得分:1)

在以下IdmTenantBoardPK中,嵌入式ID的类型和属性的名称为id

@EmbeddedId
private IdmTenantBoardPK id;

这就是o.IdmTenantBoardPK.boardId无法在查询中使用的原因。而不应使用o.id.boardId

答案 1 :(得分:0)

此处'id'是属性名称,因此请使用o.id.boardId代替o.IdmTenantBoardPK.boardId

答案 2 :(得分:0)

使用'。'操作员,我们可以在EmbeddedId字段上指定排序功能。

@Embeddable
public class ProjectId implements Serializable {

    private static final long serialVersionUID = 1L;

    @Column(name = "PROJECT_NAME")
    private String projectName;

    @Column(name = "ORGANIZATION")
    private String organization;

    ......
    ......
}

@Entity
@Table(name = "projects")
public class Project {

    @EmbeddedId
    private ProjectId projectId;

    @Column(name = "STARTED_TIME")
    private Timestamp startedTime;

    @Column(name = "ACTIVE")
    private String active;

    @Column(name = "DESCRIPTION")
    private String description;

    ......
    ......
}

如上所示,代码片段ProjectId是实体Project的组合键。我可以在组织字段上指定排序,如下所示。

Sort sort = new Sort(Direction.ASC, Arrays.asList("projectId.organization"));

演示应用程序link

答案 3 :(得分:0)

我有同样的问题。尝试一下,它就像一种魅力。

将此添加到您的实际代码中

Sort sort = Sort.by(Sort.Direction.DESC,"projectId.organization");

将此方法添加到存储库中

List<AccessoriesFile> findByorganization(String organization, Sort sort);