Saturday, April 03, 2010

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.

No comments:

Post a Comment

Thank you for your feedback