Search code examples
hibernategrailsormgrails-orm

GORM select with join


I have trouble with GORM in grails. I have two relationships, that look like this:

Company

static hasMany = [
            users:User,
]
---------
User
// no mention about entity Company

I need to get all the companies that are connected with a certain user.

    User user =  springSecurityService.currentUser

def results = Company.executeQuery("select c from Company c join User u where u.id = ${user.id}") 

SQL syntax of what I need looks like this: Select * from Company C join User u on u.company_id=c.id where u.id=user.id.

My error is: Path expected for join!

In database a new join table was created, it's name is company_user. Any idea how to write this simple select?


Solution

  • This should work

    User user = springSecurityService.currentUser
    def results = Company.executeQuery(
            "from Company c join c.users u where u.id = ?", [user.id])