LoginSignup
2
3

More than 5 years have passed since last update.

[Grails]servicesで直接SQLを実行する方法

Posted at

SQLを全部自分で書きたい!という場合はserviceの中に書いてしまいます。

まずは以下のコマンドでSerivceクラスを生成

grails create-service hogepackage.Hoge

生成されたソースを以下のよう編集。

package hogepackage

import grails.transaction.Transactional
import groovy.sql.Sql

import javax.sql.DataSource

@Transactional
class HogeService {

    def serviceMethod() {

    }

    // DataSourceをDI
    // これで現在実行中の環境(devとかtestとかprodとか)でのデータベースコネクションが利用できる。
    DataSource dataSource

    def foobar(){

        def sql = new Sql(dataSource)

        def query = """
            ここにSQLを記述
        """.toString()
        sql.rows(query)
    }

}

で、上記のサービスのメソッドをコントローラで利用する場合は以下のような形で記述する。

    // ココで、上記で作ったサービスをDI
    // メンバ変数として、単純にクラス名(サービス名)の先頭を小文字にしたものを宣言するだけ。
    def hogeService 
    def testMethodInController(){

        hogeService .foobar()

    }
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3