使用基于注释的复合主键的Hibernate createCriteria查询

时间:2016-06-03 15:38:46

标签: java hibernate composite-primary-key hibernate-annotations

在我的项目中,我在使用复合主键编写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

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

1 个答案:

答案 0 :(得分:1)

为什么需要使用别名?你试过直接访问吗?

遵循此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;
}