我是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;
}
这是来自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.
答案 0 :(得分: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.height
构造函数放置您的值PersonWell
的字段。