hibernate - 如何在Grails/GORM/Hibernate中执行特定的SQL

标签 hibernate grails hql gorm

我在Grails中有类似的域:

class Questao {

    static transients = [ "tags" ]

    String enunciado
    Double valorQuestao
    byte[] imagem
    public enum Tipo {
        ALTERNATIVAS,
        VF,
        SUBJETIVA
    }

    Tipo tipoQuestao

    static hasMany = [alternativas:Alternativas, assuntos: QuestaoAssunto, provas: Prova]

    static belongsTo = [Prova]

    static mapping = { enunciado type: 'text'}

    static constraints = {
        imagem nullable: true, maxSize: 160384
        alternativas nullable: true
    }
}

class QuestaoAssunto {

    Questao questao
    Assunto assunto

    static belongsTo = [Questao,Assunto]

}
class Assunto {

    String titulo

    static hasMany = [questoes:QuestaoAssunto]

    static belongsTo = [Questao]
}

我需要执行以下SQL:
select q.* from questao_assunto qa join questao q on q.id=qa.questao_id where assunto_id in (:assuntos_id) and q.tipo_questao = 'SUBJETIVA' GROUP BY q.id order by rand() limit 1;

:assuntos_id是一个像[5,6]的数组

如何做到这一点?

最佳答案

这是一个如何从服务执行SQL的示例。可以在 Controller 中使用相同的方法:

import groovy.sql.Sql
import groovy.sql.GroovyRowResult

class SomeService {

    // Reference to default datasource.
    def dataSource

    List<GroovyRowResult> executeQuery(assuntosId) {

        final String query = '''\
                select q.* 
                from questao_assunto qa 
                join questao q on q.id=qa.questao_id 
                where assunto_id in (:assuntos_id) 
                and q.tipo_questao = 'SUBJETIVA' 
                group by q.id 
                order by rand() 
                limit 1
        '''

        // Create new Groovy SQL instance with injected DataSource.
        final Sql sql = new Sql(dataSource)

        final results = sql.rows(query, assuntos_id: assuntosId)
        results
    }     
}

关于hibernate - 如何在Grails/GORM/Hibernate中执行特定的SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38257915/

相关文章:

maven - Grails Maven安装在Windows 7上不起作用

java - Hibernate 从表中获取具有最大字段值的单行

使用 Hibernate 的 Java Criteria Query - 生成的别名无效路径?

java - JPA CriteriaQuery 的简单 where 条件

java - grails:如何禁用<s2ui:form>标记的可调整大小的属性

Grails log4j SMTPAppender NoClassDefFoundError

java - 实体对象作为 HQL 参数

java - 从 HQL 中的时间戳提取日期以在 where 子句中进行比较

java hibernate : selecting the discriminator column in polymorphic hql query

hibernate - 使用 Spring 3 和 Servlet 3 配置 OpenSessionInViewFilter