使用findAll或HQL在Grails中加入oneToMany

时间:2013-06-23 22:03:57

标签: grails join hql gorm

我是Groovy和HQL查询的新手,但我无法在任何地方找到解决方案,所以它让我疯狂。

我有两个Domain类,它们定义了一对多的关系(用户可以有很多公司),我实际上需要(传统上称之为)'表连接',但显然是对象。

课程是这样的:

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在公司表中创建了一个user_id字段,但任何在查询中使用它的尝试都会返回错误。

那我该如何做:

select * from user u, company c, where u.id = c.user_id;

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:4)

您可以在关联中有效地使用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