0

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

那么我该怎么做:

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

做这个的最好方式是什么?

4

1 回答 1

4

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

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

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

找到所有()

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 关联

于 2013-06-23T22:47:41.057 回答