1

我是 JPQL 的新手,但我需要将一个简单的 SQL 请求翻译成 JPQL:SQL:

SELECT 
  *, 
  t.column1 + t.column2 as coefficient 
FROM 
  practice.People as t
ORDER BY coefficient

我不能使用该本机查询,因为我不知道如何将其映射到类:( 我尝试使用此 JPQL 查询:

  SELECT NEW entities.PersonWell(c.peopleId, c.name, c.age, c.height, c.weight, 1)
  FROM 
    People AS c
  ORDER BY c.age;

如何在此请求中将“1”更改为系数?我想象的唯一解决方案就是使用:

SELECT NEW entities.PersonWell(c.peopleId, c.name, c.age, c.height, c.weight, c.age + c.height)
FROM 
  People AS c
ORDER BY c.age + c.height;

但我认为这不是正确的解决方案:(我该怎么办?

脆弱的,谢谢你的回答!

但它仍然不起作用:(这是将您的答案应用于我的代码的结果:

public List<PersonWell> findWell(People person){
    String queryString = 
            "SELECT\n"
            + "NEW entities.PersonWell(c.peopleId, c.name, c.age, c.height, c.weight, c.speechspeed, "
            + "ABS(c.age - :age) + ABS(c.height - :height) + ABS(c.weight - :weight) + ABS(c.speechspeed - :speechspeed)) AS p \n" 
           +"FROM "
            + "People AS c\n"
           +"ORDER BY p.compatibility DESC";
    Query query = em.createQuery(queryString);
    query.setParameter("age", person.getAge());
    query.setParameter("height", person.getHeight());
    query.setParameter("weight", person.getWeight());
    query.setParameter("speechspeed", person.getSpeechspeed());
    List<PersonWell> resultList = query.getResultList();
    return resultList;
}

Ans 这是来自 glassfish 服务器的答案:

java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Error compiling the query [SELECT
NEW entities.PersonWell(c.peopleId, c.name, c.age, c.height, c.weight, c.speechspeed, ABS(c.age - :age) + ABS(c.height - :height) + ABS(c.weight - :weight) + ABS(c.speechspeed - :speechspeed)) AS p 
FROM People AS c
ORDER BY p.compatibility DESC], line 4, column 9: invalid navigation expression [p.compatibility], cannot navigate expression [p] of type [entities.PersonWell] inside a query.
4

1 回答 1

0

像这样的东西对你不起作用?

SELECT NEW entities.PersonWell(c.peopleId, c.name, c.age, c.height, c.weight, c.age + c.height) AS p
FROM 
  People AS c
ORDER BY p.coefficient;

使用构造函数p.coefficient将值 放在哪里的字段在哪里。c.age + c.heightPersonWell

于 2013-03-06T10:38:30.780 回答