我们在使用Grails(2.3.7)时遇到问题,它与Criteria Queries和映射有关。问题是在定义标准并尝试列出结果之后,Hibernate似乎没有将映射表添加到查询中,因此查询失败。
现在我们有3个相关的表:Users,Competitions + UserCompetition,它们在具有复合主键的其他2个表之间具有关系,并且将每两个表作为外键引用。
这里有我们域名的定义:
class User {
(...)
static hasMany = [competitions:Competition]
static mapping = {
table "users"
(...)
competitions joinTable: [name: 'usersCompetitions',
key: 'userId',
column: 'competitionId']
}
class Competition {
(...)
static hasMany = [users:User]
static belongsTo = User
static mapping = {
table "competitions"
id column: 'competitionId'
users joinTable: [name: 'usersCompetitions',
key: 'competitionId',
column: 'userId']
}
}
class UserCompetition implements Serializable {
private static final long serialVersionUID = 1
Competition competition
User user
boolean planning
static mapping = {
table "usersCompetitions"
id composite: ['user', 'competition']
competition column: 'competitionId'
user column: 'userId'
}
boolean equals(other) {
if (!(other instanceof UserCompetition)) {
return false
}
other.user?.id == user?.id &&
other.competition?.id == competition?.id
}
int hashCode() {
def builder = new HashCodeBuilder()
if (user) builder.append(user.id)
if (competition) builder.append(competition.id)
builder.toHashCode()
}
static UserCompetition get(long userId, long competitionId) {
UserCompetition.where {
user == User.load(userId) &&
competition == Competition.load(competitionId)
}.get()
}
}
最后,我们尝试使用Criteria从UserCompetitions中检索一些数据:
def c = UserCompetition.createCriteria()
def competitions = c.list{
createAlias("competition", "comp")
and{
isNotNull("comp.startDate")
gt("comp.startDate", now)
}
eq("user.id",user.id)
ne("planning",true)
maxResults(3)
order("comp.startDate", "asc")
}
这就是我们得到的:
Message: Unknown column 'comp1_.startDate' in 'where clause'
这是Hibernate生成的查询,正如您所看到的,它没有添加与Competition表的关系:
select this_.userId as userId0_0_, this_.competitionId as competit2_0_0_, this_.planning as planning0_0_ from usersCompetitions this_ where (comp1_.startDate is not null and comp1_.startDate>?) and this_.userId=? and this_.planning<>? order by comp1_.startDate asc limit ?
我们正在努力了解最新情况,但我们无法理解为什么Hibernate没有将映射表添加到查询中: - ?
提前致谢,
答案 0 :(得分:0)
问题与Grails如何解释使用joinTable
的所有映射有关。
我们删除了joinTable
和User
域类中的所有Competition
个引用,并通过UserCompetition
而不是彼此链接它们,并且查询开始起作用。< / p>
class User {
(...)
static hasMany = [competitions:UserCompetition]
static mapping = {
table "users"
(...)
/* competitions joinTable: [name: 'usersCompetitions',
key: 'userId',
column: 'competitionId'] */
}
class Competition {
(...)
static hasMany = [users:UserCompetition]
static belongsTo = User
static mapping = {
table "competitions"
id column: 'competitionId'
/* users joinTable: [name: 'usersCompetitions',
key: 'competitionId',
column: 'userId'] */
}
}