将本机SQL查询的结果映射到Grails域类

Oli*_*old 17 grails hibernate

是否可以将本机SQL查询的结果映射到Grails域类实例的集合?

Oli*_*old 19

import com.acme.domain.*

def sessionFactory
sessionFactory = ctx.sessionFactory  // this only necessary if your are working with the Grails console/shell
def session = sessionFactory.currentSession 

def query = session.createSQLQuery("select f.* from Foo where f.id = :filter)) order by f.name");
query.addEntity(com.acme.domain.Foo.class); // this defines the result type of the query
query.setInteger("filter", 88);
query.list()*.name;
Run Code Online (Sandbox Code Playgroud)


小智 8

或者在Grails应用程序中使用Groovy SQL

import  groovy.sql.Sql

class TestQService{

    def dataSource  //Auto Injected

    def getBanksForId(int bankid){

        def sql = Sql.newInstance(dataSource)

        def rows = sql.rows(""" Select BnkCode , BnkName from Bank where BnkId = ?""" , [bankid]) 

        rows.collect{
            new Bank(it)
        }

    }


    class Bank{

        String BnkCode
        String BnkName

        }

}
Run Code Online (Sandbox Code Playgroud)