Query data not in domain classes

This is how you would query from outside tables not contained in the domain classes.

Declare dataSource variable in the controller and Grails will inject the data source

class MyController {
    def dataSource

   
   
Use the dataSource variable to query as below:-

    def myMethod(int a){
        groovy.sql.Sql sql = new groovy.sql.Sql(dataSource)

        String query= “select count(*) as count from table_name where column_name =”+a;
        def result = sql.firstRow(query);

        if(result?.count>0){
            return true
        }else{
            myInstance.errors.rejectValue(“domainVariable”, “Combination does not exist”)
        }
    }

   
There are other ways to query like below:-
        def result = []
        sql.eachRow(“select distinct(column_name) from table_name where column2_name=?”,[params.param2_name],{ row ->
                result << row.column_name
            });

           
Make sure you check out the groovy.sql.Sql javadoc for more options to query.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s