使用findAll或HQL在Grails中实现一个oneToMany连接
我是Groovy和HQL查询新手,但我在任何地方都找不到解决方案,所以这让我发疯 我有两个定义了一对多关系的域类(一个用户可以有多个公司),我实际上需要做(传统上称之为“表连接”,但显然需要对象 课程安排如下:使用findAll或HQL在Grails中实现一个oneToMany连接,grails,join,hql,gorm,Grails,Join,Hql,Gorm,我是Groovy和HQL查询新手,但我在任何地方都找不到解决方案,所以这让我发疯 我有两个定义了一对多关系的域类(一个用户可以有多个公司),我实际上需要做(传统上称之为“表连接”,但显然需要对象 课程安排如下: class User { transient springSecurityService static hasMany = [company: Company] String username String password boolean e
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\u id
字段,但在查询中使用该字段的任何尝试都会返回错误
那么,我将如何做类似于:
User.findAll("from User as u inner join fetch u.company as companies where u.accountExpired = true", [max: 10, offset: 5])
从用户u、公司c中选择*,其中u.id=c.user\u id代码>
执行此操作的最佳方法是什么?您可以在关联上有效地使用join
,例如:
User.findAll("from User as u inner join fetch u.company as companies where u.accountExpired = true", [max: 10, offset: 5])
HQL
select*from User as u internal join fetch u.company as companys,其中u.id=?
请注意,在查询中使用fetch
将急切地为用户
获取公司
的关联集合
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])
为了得到一个具体的实现并真正了解细节,我坚持要看一看和。您可以在关联上有效地使用join
,例如:
User.findAll("from User as u inner join fetch u.company as companies where u.accountExpired = true", [max: 10, offset: 5])
HQL
select*from User as u internal join fetch u.company as companys,其中u.id=?
请注意,在查询中使用fetch
将急切地为用户
获取公司
的关联集合
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])
为了得到一个具体的实现,并真正了解细节,我坚持要看一看和。感谢您提供了这样一个结构良好且有用的回复。您的回答对解决此问题非常有帮助。@user2181809很高兴它有帮助。你可以通过接受答案来帮助他人。谢谢你这样一个结构合理、有用的回答。您的回答对解决此问题非常有帮助。@user2181809很高兴它有帮助。你可以通过接受答案来帮助他人。