0

I'm new to Grails and I'm stuck with this problem for hours. Thanks in advance for you help!

Here is my question:

I have a database with two tables

  1. PROJECT
  2. LIKES

As you can guess a user has the right to Like a Project. In the Domain Class Project there is NO relations (belongsTO, hasOne, etc..) Same in the Domain Class Likes

In the database the table LIKES has a field project_id but it is not set as a foreign_key. It is this made this way for right purpose.

Now I need to execute a native SQL query with grails which is really simple and returns the result expected.

The result is all projects that have Likes or not

Here is the query :

SELECT project.name, Likes.likes
FROM project
LEFT JOIN Likes
ON project.id = likes.project_id;

I cant find a way to convert this SQL query to HQL. It seems that HQL works on Domain instance and the fact that there is no relation between the domains return an error like "the Domain Project has no Likes attribute" which is correct.

Is there a way to get the right result with one query or do I need to do two query and build an Array with the result programmatically ?

Thanks for you help

4

2 回答 2

3

如您所见,如果您的域类没有关系,则无法使用HQL.

但在 Grails 中,您可以使用groovy.sql.Sql. 服务示例:

class MyService {
  def dataSource

  void addNewRecord(String data) {
    groovy.sql.Sql sql = new Sql(dataSource)
    sql.execute("insert into my_table(my_anydata_clomn) values(sys.anyData.convertVarchar2(?))",[data])
  }

}
于 2013-10-18T12:00:28.373 回答
1

好的,它是这样工作的:)

 def dataSource

    def getProjectList() {
        groovy.sql.Sql sql = new groovy.sql.Sql(dataSource)
        log.info(sql)
        log.info("datasource " + dataSource)
        def t = sql.rows("SELECT * \n" +
                "FROM project\n" +
                "LEFT JOIN Likes\n" +
                "ON project.id=likes.project_id\n" +
                "ORDER BY likes.likes")
        sql.close()
        return t;
    }
于 2013-10-18T12:41:22.360 回答