【问题标题】:A oneToMany join in Grails using findAll or HQL使用 findAll 或 HQL 在 Grails 中加入 oneToMany
【发布时间】:2013-06-23 22:03:57
【问题描述】:

我是 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;

最好的方法是什么?

【问题讨论】:

    标签: grails join hql grails-orm


    【解决方案1】:

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

    HQL
    select * from User as u inner join fetch u.company as companies where u.id = ?

    请注意,在查询中使用fetch 会急切地获取companies 的关联集合以获取user

    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

    【讨论】:

    • 感谢您提供如此完善和有用的回复。您的回复对解决此问题很有帮助。
    • @user2181809 很高兴它有帮助。您可以通过接受答案使其对其他人有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2012-02-08
    相关资源
    最近更新 更多