grails - 使用findAll或HQL在Grails中加入oneToMany

标签 grails join hql gorm

我是Groovy和HQL查询的新手,但是我在任何地方都找不到解决方案,因此它使我发疯。

我有两个域类,它们定义了一对多的关系(一个用户可以有很多公司),我确实需要做(一个传统上被称为)“表联接”,但显然是对象。

这些类是这样的:

class User {
    transient springSecurityService

    static hasMany = [company: Company]

    String username
    String password
    boolean enabled
    boolean accountExpired
    boolean accountLocked
    boolean passwordExpired
    ...
    ...
    ...
}

...以及公司类别
class Company {
    static scaffolding = true

    String name
    String address1
    String address2
    String address3
    String address4
    String postCode
    String telephone
    String mobile // mobile number to receive appointment text messages to
    String email // email address to receive appointment emails to  

    static hasMany = [staff: Staff]
    static belongsTo = [user: User]

    ...
    ...
    ...
}

Gorm在company表中创建了user_id字段,但是任何在查询中使用此字段的尝试都会返回错误。

那么我该怎么做:
select * from user u, company c, where u.id = c.user_id;
做这个的最好方式是什么?

最佳答案

您可以在关联上有效地使用join,例如:

HQL select * from User as u inner join fetch u.company as companies where u.id = ?
请注意,在查询中使用fetch会急切地获取companiesuser的相关集合

findAll()

User.findAll("from User as u inner join fetch u.company as companies where u.id = ?", [1])

使用findAll代替HQL的好处是您可以轻松实现分页,例如:
User.findAll("from User as u inner join fetch u.company as companies where u.accountExpired = true", [max: 10, offset: 5])

为了获得具体的实现并真正理解细节,我坚持要看看findAllHQL associations

关于grails - 使用findAll或HQL在Grails中加入oneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265770/

相关文章:

java.lang.Object 无法转换

mysql - 使用 gorm 映射现有的 mysql 数据库

database - 如何从 Grails Controller 操作中在当前系统中创建文件并保存从数据库中获取的数据?

php - 如何在 mysqli 准备语句中使用多个内部连接和多个 WHERE 子句?

hibernate - 如何在grails中加入Hibernate上的2表?

java - 如何在HQL中转义关键字 "on"

rest - Grails 3 应用程序中 POST 中的 header 不会随其余服务一起发送

grails - 在索引中创建Grails列表

sql - DB2 SQL 连接和最大值

php - 尝试解决 MySQL 查询逻辑问题的新手