简体   繁体   English

在HQL中指定字段列表似乎不起作用

[英]Specifying a list of fields in HQL doesn't seem to work

I have the following HQL in Hibernate using Spring MVC. 我在使用Spring MVC的Hibernate中具有以下HQL。

List<Colour>list=session.createQuery("from Colour order by colourId desc")
.setFirstResult((currentPage-1)*rowsPerPage)
.setMaxResults(rowsPerPage).list();

It works and returns a list of rows from the colour table (actually operates upon the Colour entity (POJO) that I can understand) in Oracle 10g. 它可以工作并从Oracle 10g中的颜色表中返回行列表(实际上是对我能理解的颜色实体(POJO)进行操作)。

What if I need to retrieve a list fields, I'm trying the following. 如果需要检索列表字段怎么办,请尝试以下操作。

List<Colour>list=session.createQuery("colourId, colourName, colourHex from Colour order by colourId desc")
.setFirstResult((currentPage-1)*rowsPerPage)
.setMaxResults(rowsPerPage).list();

It ends with an excpetion 它以惊险结束

java.lang.IllegalArgumentException: node to traverse cannot be null!

In some articles, it was mentioned that the following version of HQL should (or may) work 在某些文章中,提到了以下版本的HQL应该(或可能)起作用

List<Colour>list=session.createQuery("select colourId, colourName, colourHex from Colour order by colourId desc")
.setFirstResult((currentPage-1)*rowsPerPage)
.setMaxResults(rowsPerPage).list();

but unfortunately, it also didn't work for me. 但不幸的是,它对我也不起作用。 Using the createSQLQuery() method to execute native SQL would work but I want to stick to the createQuery() method with HQL unless it's absolutely necessary. 使用createSQLQuery()方法执行本机SQL是可以的,但是除非绝对必要,否则我想坚持使用HQL的createQuery()方法。 How can I specify a list of fields in HQL? 如何在HQL中指定字段列表?

I agree with yorkw's comment. 我同意约克的评论。 If you select properties in your query then you cannot ask for a List<Colour> object to be returned from a call to .list() . 如果在查询中选择属性,则无法要求通过调用.list()返回List<Colour>对象。

Instead you should do this 相反,您应该这样做

    List<Object[]> rows = session.createQuery("select c.colourId, c.colourName, c.colourHex " +
        " from Colour c " + 
        " order by c.colourId desc").list();

Then iterate over the list object and instantiate your objects. 然后遍历列表对象并实例化您的对象。 Or whatever you need to do. 或您需要执行的任何操作。

    for ( Object[] row : rows ) {
        Long colourId = (Long)row[0];
        // ... etc
    }

Why don't you try creating a map? 您为什么不尝试创建地图? Something like this: 像这样:

SELECT NEW MAP( colour.colourId AS id
              , colour.colourName AS name ...) 
  FROM Colour colour 
  ORDER BY colour.colourId

I use the alias for Colour "colour" so hibernate knows from which entity is the property I am referencing, I am implying all those properties are from the same entity, if not, then check your referencing! 我使用别名“ Color”作为颜色,因此休眠知道我所引用的属性来自哪个实体,这意味着所有这些属性都来自同一实体,如果不是,则检查您的引用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM