2016-07-08 18 views
1

我有這樣的領域中的Grails:我如何在Grails的/格姆/休眠執行specifc SQL

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]

怎麼能這樣?

回答

1

以下是如何從服務執行SQL的示例。同樣的方法也可以在控制器中使用:

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 
    }  
} 
1

也許你有一個理由自行定義聯接表,但我的做法是:

class Questao { 

    static transients = [ "tags" ] 

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

    Tipo tipoQuestao 

    static hasMany = [assuntos: Assunto] 

    static mapping = { 
     enunciado type: 'text' 
     assuntos joinTable:[name:"questao_assunto", key:'assunto_id' ] 
    } 

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

class Assunto { 

    String titulo 

    static hasMany = [questoes:Questao] 

    static belongsTo = [Questao] 

    static mapping = { 
     questoes joinTable:[name:"questao_assunto", key:'questao_id' ] 
    } 
} 

和要執行的SQL,我會嘗試像下面這樣:

def records = Questao.findAll { 
    tipoQuestao == Questao.Tipo.SUBJETIVA 
    && assuntos { id in [1 as long,2 as long,3 as long] } 
} 

,或者如果你想通過1

def records = Questao.find(order: 'xxx') { ... } 
0秩序和限制