概述
今天在学习条件查询过程中,关联的表总是报错,折腾了一个多小时,终于解决了。
情景再现:
=====================================
在src/groovy/command目录下新建SearchMemberCommand.groovy类
(类必须有包,否则IDEA调不到)
*command.groovy类(以command结尾)不会持久化,可用于不需要持久化或者和domain无关的action
class SearchMemberCommand {
String teamName
String name
String gender
Team team
}
-------------------------------------
MemberController
def search = {SearchMemberCommand cmd ->
if(request.method == "POST"){
def criteria = Member.createCriteria()
def resultList = criteria{
and{
if(cmd.name)
like('name',"%${cmd.name}%")
if(cmd.gender)
like('gender',"${cmd.gender}")
if(cmd.team.id) {
Team{
eq('id', "${cmd.team.id}" as Long)
}
fetchMode('team.id', FetchMode.EAGER)
}
}
order("id","desc")
}
respond resultList, view: "index"
}else{
Member memberInstance = new Member()
respond memberInstance
}
}
-------------------------------------
member/search.gsp
<g:select name="gender" from="${memberInstance.constraints.gender.inList}" value="${memberInstance?.gender}" />
=====================================
报错:
=====================================
解决方法:
把查询中的Team改为team
=====================================
Team.groovy
package webquick
class Team {
String teamName
Date foundDate
static constraints = {
teamName(size:3..50,blank: false,unique: true)
}
static hasMany = [members:Member]
String toString(){
return teamName
}
static mapping = {
table("TEAM")
}
}
=====================================
Member.groovy
package webquick
class Member {
Team team
String name
String gender = 'F'
String address
String email
String phone
static belongsTo = [Team]
static constraints = {
name(size: 3..20,blank: false,unique: true)
email(email: true,blank: false)
gender(inList: ["F","M"])
}
static mapping = {
table("MEMBER")
}
}
=====================================
原因:
Member属于Team,所以Member中存在Team的外键,并且team是Member的
一个变量,故team小写,程序会认成Member.team,不能写成类名,只能是类的一个变量
=====================================
拓展:
Team中的toString()方法作用:
String toString(){
return teamName
}
--------------------------------------------
如果toString()方法改为:
String toString(){
return foundDate
}
=====================================
最后
以上就是开朗向日葵为你收集整理的groovy多表关联查询的全部内容,希望文章能够帮你解决groovy多表关联查询所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复