在我的项目中,我很难用复合主键编写createCriteria查询。我的实体类和DAO方法如下:

    @Entity
    @Table(name="METRICS")

public class Metrics implements Serializable {

    private static final long serialVersionUID = -2580493160757497919L;

    @EmbeddedId
    protected MetricsID metricsID;

    @Column(name="PROJ_PERF")
    private String proj_perf;

    @Column(name="ANALYSIS")
    private String analysis;

    public String getProj_perf() {
        return proj_perf;
    }

    public void setProj_perf(String proj_perf) {
        this.proj_perf = proj_perf;
    }

    public String getAnalysis() {
        return analysis;
    }

    public void setAnalysis(String analysis) {
        this.analysis = analysis;
    }

    public MetricsID getMetricsID() {
        return metricsID;
    }

    public void setMetricsID(MetricsID metricsID) {
        this.metricsID = metricsID;
    }

}

@Embeddable
public class MetricsID implements Serializable {

    private static final long serialVersionUID = 4691163770334366543L;

    @Column(name="PROJECT_ID")
    private String project_id;

    @Column(name="METRICS_NO")
    private int metrics_no;

    public String getProject_id() {
        return project_id;
    }

    public void setProject_id(String project_id) {
        this.project_id = project_id;
    }

    public int getMetrics_n0() {
        return metrics_no;
    }

    public void setMetrics_no(int i) {
        this.metrics_no = i;
    }
}

    @Override
    @Transactional
    public List<Metrics> viewMetrics(String project_id) throws Exception {
        List<Metrics> metrics = (List<Metrics>)sessionFactory.getCurrentSession().
                createCriteria(Metrics.class).createAlias("metricsID.project_id", "project_id_alias").
                add(Restrictions.eqProperty("project_id_alias.project_id", project_id)).list();
        return metrics;
    }

我收到的错误是- org.hibernate.QueryException:不是关联:metricsID.project_id

我搜索了几个类似的示例,并根据一个搜索结果的建议使用了别名,但这是我第一次使用别名。我究竟做错了什么?

最佳答案

为什么需要使用别名?您是否尝试过直接访问?

在此example之后,此代码应该工作

@Override
@Transactional
public List<Metrics> viewMetrics(String project_id) throws Exception {
    List<Metrics> metrics =
      (List<Metrics>) sessionFactory.getCurrentSession()
                                    .createCriteria(Metrics.class)
                                    .add(Restrictions.eq("metricsID.project_id", project_id))
                                    .list();
    return metrics;
}

08-07 19:21