-1

Working on grails 3 application. My domain structure is defined below:

Job{
Integer id
String title   
Date publishedDate
}

JobType{
Integer id
String name

}

JobJobTypeMap{
  String jobId
  String jobTypeId
}

For example,

**Job**
id title
1  job1
2  job2

**JobType**
id name
 1 govt
 2 private

**JobJobTypeMap**
jobId jobTypeId
1      1
1      2
2      2

I need to get list of jobs (offset and max attributes and order published date descending) with particular jobType.

Kindly, don't ask me to change the domain structure.

Any suggestions would be appreciated

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Amarnath R
  • 973
  • 3
  • 14
  • 33

3 Answers3

1

You are not defining properly the domain classes. You don't have to create the relation class between Job and JobType, Grails will do it automatically on you DB.

Job{
Integer id
String title   
Date publishedDate
JobType jobType
}

JobType{
Integer id
String name

}

List<Job> jobs = Job.findAllByJobType(jobTypeInstance, [sort: '', order:'', max: '', offset: ''])
quindimildev
  • 1,280
  • 8
  • 21
1

You have to use Grails SQL/HSQL to query the DB.

In controller

def getList() {

    def params = [column:"job.title", order:'DESC', offset:0, limit:5]

    Sql sql = new Sql(dataSource)
    String query = """
        SELECT  job_job_type_map.job_id jobId, job_job_type_map.job_type_id jobTypeId,
                job.title jobTitle, jobType.name jobTypeName
        FROM    job job, job_type jobType, job_job_type_map job_job_type_map
        WHERE   job_job_type_map.job_id = job.id
        AND     job_job_type_map.job_type_id = jobType.id
        ORDER BY ${params.column} ${params.order}
        LIMIT   :limit
        OFFSET  :offset
    """

    List<GroovyRowResult> result  = sql.rows(query, params)
    result.each {
        println "${it.jobId} ${it.jobTypeId} ${it.jobTitle} ${it.jobTypeName}"
    }

    render template: 'list', model: [jobRows:result]
}

in GSP

<g:each in="${jobRows}" var="job">
    "${job.jobId} ${job.jobTypeId} ${job.jobTitle} ${job.jobTypeName}" <br/>
</g:each>

Be careful ORDER BY ${params.column} ${params.order} There is restriction in using named parameter in some places. You can find here

Enjoy!

Community
  • 1
  • 1
devbd
  • 431
  • 3
  • 12
  • Also you can see some more solutions on https://github.com/mdaynul/jobproject4StackOverflow with HSQL and class biniding. – devbd Apr 19 '16 at 22:47
0

If you do not want to change domain structure and do not want to write SQL/HSQL then you can use this approach:

def jobTypeId = JobType.findByName(params.jobTypeName).id
def jobIdList = JobJobTypeMap.findAllByJobTypeId(jobTypeId)?.jobId
def jobList = Job.createCriteria().list(max:max, offset:offset) {
  'in'("id", jobIdList)
  order("publishedDate", "desc")
}

jobList will give you the list of all jobs with specific job type, max, offset and order by publishedDate.

Ghata.Shah
  • 11
  • 5