如何编写SQL语句 - hibernate / persistence查询异常 - 无法解析属性

时间:2012-08-23 20:09:22

标签: java sql hibernate persistence hql

我是Hibernate和SQL的新手,所以我可能做错了什么并且不会看到它 - 即使现在已经花了第二天了:

在我的PostgreSQL数据库中,我有两个表:

PieChartResult
+---------+---------+--------------+-------+----------+----------+----------------+
| id      | answer  | approvalrate | input | worktime | workerid | piecharthit_id |
+---------+---------+--------------+-------+----------+----------+----------------+


PieChartHit
+---------+-----------+
| id      | truevalue |
+---------+-----------+

然后我在SQL语句后面写了pgAdmin,它完全可以正常工作:

 SELECT DISTINCT input, answer FROM piecharthit INNER JOIN piechartresult ON piecharthit.id=piechartresult_piecharthit_id;

我得到一个结果表,其中我看到了每个输入的所有收集的答案。

当我尝试在java中编写相同的语句时

Query q = em.createQuery(SELECT DISTINCT a FROM PieChartHit a INNER JOIN a.PiechartResult b WHERE a.id=b.piecharthit_id")

我得到一个例外:

Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: PieChartResult of: PieChartHit [SELECT DISTINCT a FROM PieChartHit a INNER JOIN a.PieChartResult b WHERE a.id=b.piecharthit_id]
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1364)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:294)
at Driver.main(Driver.java:37)
Caused by: org.hibernate.QueryException: could not resolve property: PieChartResult of: PieChartHit [SELECT DISTINCT a FROM PieChartHit a INNER JOIN a.PieChartResult b WHERE a.id=b.piecharthit_id]

这两个类看起来像这样:

@Entity
@Table(name="PieChartResult")
public class PieChartResult {

@Id
@GeneratedValue
private Long id;

private String workerID;
private String approvalRate;
private String input;
private double answer;

@ManyToOne
private PieChartHit piecharthit;

@Entity
@Table(name="PieChartHIT")
public class PieChartHit {

@Id
@GeneratedValue
private Long id;

private double trueValue;
有人请指导这个迷失的灵魂吗? :(

2 个答案:

答案 0 :(得分:0)

对于初学者,你应该编写HQL,而不是SQL。这意味着您使用类/字段名称而不是表/列名称。请注意,该例外表示"无法解析属性"。

此外,您在查询行中的hql字符串周围缺少引号。

根据您的代码编辑,您从PieChartHit引用PieChartResult进行选择,但看起来这种关系不是双向的。还

@Table(name="PieChartHIT")

看起来你有大写问题。

答案 1 :(得分:0)

这是对原始评论的继续 它显示了如何将结果抓取到列表中.. 我认为您需要更改PieChartResultPieChartHit的类定义才能使hibernate正常工作。

String hql = "from CrawlerElement e where request.id = :requestId";
Query q = getSession().createQuery(sql); //getSession is not the actual method.
q.setParameter("requestId", id);
elements = q.list(); //elements is a List<CrawlerElement> where CrawlerElement which is actual @Entity
return elements;