我是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
会急切地获取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])
为了获得具体的实现并真正理解细节,我坚持要看看findAll和HQL associations。
关于grails - 使用findAll或HQL在Grails中加入oneToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17265770/