如何显示HQL结果以在grails中查看。

时间:2016-12-28 02:33:26

标签: grails groovy hql

我有两个简单的类Staff和Department,我想按部门列出人员,然后使用HQL在视图中显示。

首先,这些是Domain classes Staff and Department

class Staff {
 String fullName
 String dateOfBirth

 static belongsTo = [department: Department]

}

class Department {
  String department

  static hasMany = [staff: Staff]
}

部门有海,陆,空等实例。

这是一个StaffController.groovy(例如,只有listbysea行动)

def listbysea() {
      params.max =  Math.min(params.max ? params.int('max') : 10, 100)

      //Query
      def staffList = Staff.executeQuery("SELECT s.fullName from Staff s join s.department d WHERE d.department = 'Sea')
      [staffInstance: staffList, staffInstanceTotal: staffList.size()]
    }

这是我的listbysea.gsp

<table class="table table-striped table-hover table-bordered">
        <thead>
            <tr>
                <g:sortableColumn property="fullName" title="${message(code: 'staff.fullName.label', default: 'Full Name')}" />

                <g:sortableColumn property="dateOfBirth" title="${message(code: 'staff.dateOfBirth.label', default: 'Date of Birth')}" />

            </tr>
        </thead>
        <tbody>
            <g:each in="${staffList}" status="i" var="staffInstance">
                <tr class="${(i % 2) == 0 ? 'even' : 'odd'}">

                <td style="vertical-align: middle;"><g:link action="show" id="${staffInstance.id}"> ${fieldValue(bean: staffInstance, field: "fullName")}</g:link></td>

                <td style="vertical-align: middle;">    ${fieldValue(bean: staffInstance, field: "dateOfBirth")}</td>

                </tr>
            </g:each>
      </tbody>
   </table>

但是,表中没有显示数据,我不确定查询是否确实不会产生任何结果,或者视图是否存在问题。所以我问我是否在将查询结果返回给视图时做了正确的事情。我甚至尝试了这个查询

def staffList = Staff.executeQuery("SELECT new map(s.fullName as fullName, d.department as department)\
         FROM Staff as s, Department as d \
         WHERE s.department = d HAVING s.department = ('Sea')")

但仍然没有显示结果。

欣赏任何提示。

1 个答案:

答案 0 :(得分:0)

控制器中的变量名与gsp文件使用的名称不匹配。

在控制器中,您使用staffInstance

def staffList = Staff.executeQuery("SELECT s.fullName from Staff s join s.department d WHERE d.department = 'Sea')
[staffInstance: staffList, staffInstanceTotal: staffList.size()]

但是在gsp中你使用staffList

<g:each in="${staffList}" status="i" var="staffInstance">

尝试将控制器更改为:

[staffList: staffList, staffInstanceTotal: staffList.size()]