我创建了两个表,一个是Category,一个是Manufacturer,它们的关系是多对多,所以我使用连接表,我分别向两个表中插入值。现在我想通过id连接两个表,但是我做不到,你能帮我....吗当我尝试在连接表中插入值时,给出一个异常,下面是异常:
Cannot invoke method addToManufacturers() on null object. Stacktrace follows:
java.lang.NullPointerException: Cannot invoke method addToManufacturers() on null object
这是Category
的域类static hasMany = [manufacturers: Manufacturer]
static constraints = {
name blank: false, size: 0..60, unique: false
}
static mapping = {
table 't01i001'
id column: 'f_category_id'
name column: 'f_name', length: 30
version column: 'f_revision'
manufacturers joinTable: [name: 't01j001', key: 'k_category_id', column: 'k_manufacturer_id']
}
这是我的域类制造商
static belongsTo = Category
static hasMany = [categories: Category]
static constraints = {
name blank: false, size: 0..60, unique: false
}
static mapping = {
table 't01i002'
id column: 'f_manufacturer_id'
name column: 'f_name', length: 30
version column: 'f_revision'
categories joinTable: [name: 't01j001', key: 'k_manufacturer_id', column: 'k_category_id']
}
添加我的控制器,我试图插入
def manuInsertInCat(){
def message, flag,count=0,categories = []
int catid = params.containsKey("catid") ? params.catid : '0'
int manuid = params.containsKey("manuid") ? params.manuid : '0'
def category = Category.get(catid);
def manufacture = Manufacturer.get(manuid)
category.addToManufacturers(manufacture)
message = "Successfully Loaded"
count++
flag =true
render Category.getJsonData(categories, count, flag, message)
}
最后我通过这个过程完成了我的工作,效果很好。
def catInsertInManu(){
def message, flag,count=0,manufacturers = []
String catid = params.containsKey("catid") ? params.catid : '0'
String manuid = params.containsKey("manuid") ? params.manuid : '0'
def category = Category.get(catid)
def manufacture = Manufacturer.get(manuid)
manufacture.addToCategories(category)
def m01i001001s = []
manufacture.categories.each{ cat ->
m01i001001s << [id:cat.id, name:cat.name]
}
manufacturers << [id: manufacture.id, name:manufacture.name, m01i001001s:m01i001001s]
message = "Successfully Loaded"
count++
flag =true
render Manufacturer.getJsonData(manufacturers, count, flag, message)
}