我有一张桌子"问题"其中包含字段ID,版本以及其他字段。一个问题可以有多个具有相同ID和不同版本的记录。我需要为每个问题选择最高版本的问题记录。
我的SQL查询是
select * from questions v1 inner join
(select id, max(version) as highest_version from
questions group by id
)as v2 on v1.id = v2.id and v1.version = v2.highest_version;
此查询适用于Sequel pro。但我需要从Java运行它,我正在使用hibernate。
我的Java代码是:
String assertQuestionQuery = "select v1 from Question v1 inner join "
+ "(select t.id, max(t.version) as highest_version "
+ "from Question t "
+ "group by t.id) "
+ "as v2 on v1.id = v2.id and v1.version = v2.highest_version";
Query q = sourceEm.createQuery(assertQuestionQuery, Question.class);
List<Question> questionVersions = q.getResultList();
我收到以下错误:
ERROR org.hibernate.hql.internal.ast.ErrorCounter line 1:87: unexpected token: (
如果我删除括号,我收到以下错误:
ERROR org.hibernate.hql.internal.ast.ErrorCounter line 1:87: unexpected token: select
答案 0 :(得分:1)
createQuery
用于创建JPA / HQL查询,请尝试使用createNativeQuery
。
答案 1 :(得分:0)
我经常使用Native SQL Query,如下所示:
@Override
public List<MyObj> findListNew() {
Session session = null;
Transaction tx = null;
List<MyObj> objects = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
// Write Native SQL here
StringBuffer SqlCommand =new StringBuffer();
SqlCommand.append("select * \n");
SqlCommand.append(" from tableA a , tableB b \n");
SqlCommand.append(" where a.tb_id = b.id; ");
// Map SQL results to your class MyObj
SQLQuery query = (SQLQuery) session.createSQLQuery(SqlCommand.toString())
.addScalar("AttributeOfMyObj",IntegerType.INSTANCE)
.setResultTransformer(Transformers.aliasToBean(MyObj.class));
objects = query.list();
tx.commit();
} catch (HibernateException e) {
} catch (Exception e) {
} finally {
if (session != null)
session.close();
}
return objects;
}
你可以找到更多的指示&amp; Hibernate官方网站上的示例:https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html
答案 2 :(得分:0)
尝试以下更改。
createNativeQuery(..)
代替createQuery(..)
select v1.* from...
代替select v1 from...