【发布时间】:2013-11-26 20:39:37
【问题描述】:
使用 Grails 2.2.4。和构建测试数据:2.0.5。我无法使用 conf - Bootstrap.groovy 在数据库中添加多对多实例。使用 MySQL 作为数据库。
这是简化的域类:
class Reseller {
String resellerName
static hasMany = [addresses: Address]
}
和
class Address {
String address1
static hasMany = [resellers: Reseller]
static belongsTo = [Reseller]
}
这会导致在运行时在 MySQL 中创建...
(下面是一个简单的 ER 图,因为我无法从 MySQL Workbench Diagram 发布图像)
经销商 ==> 1 对多==> reseller_address
如果不存在则创建表 address (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) 非空,
address1 varchar(255) 非空,
主键 (id)
) ENGINE=InnoDB 默认字符集=utf8 AUTO_INCREMENT=1 ;
如果不存在则创建表 reseller (
id bigint(20) NOT NULL AUTO_INCREMENT,
version bigint(20) 非空,
reseller_name varchar(255) 非空,
主键 (id)
) ENGINE=InnoDB 默认字符集=utf8 AUTO_INCREMENT=2 ;
如果不存在则创建表 reseller_addresses (
address_id bigint(20) 非空,
reseller_id bigint(20) 非空,
主键 (reseller_id,address_id),
键FK3F39FB15CB44906F (reseller_id),
键FK3F39FB1541937EA5 (address_id)
) ENGINE=InnoDB 默认字符集=utf8;
更改表reseller_addresses
添加约束FK3F39FB1541937EA5外键(address_id)参考address(id),
添加约束 FK3F39FB15CB44906F 外键 (reseller_id) 引用 reseller (id);
这是 Bootstrap.groovy:
import grails.buildtestdata.mixin.Build
import manytomany.*
class BootStrap {
def init = { servletContext ->
Address ad1 = Address.build()
Reseller rs1 = Reseller.build()
//comment out next line to run and see tables being built.
rs1.addToAddresses(address: ad1) //does not work. see error below
}
def destroy = {
}
}
上面的结果会导致下面的错误。它还导致数据库中的零表在 MySQL 中。我可以看到它们被创建,然后它们在下面的错误中消失。
| Running Grails application
Hibernate: insert into address (version, address1) values (?, ?)
Hibernate: insert into reseller (version, reseller_name) values (?, ?)
| Error 2013-11-13 17:37:01,543 [localhost-startStop-1] ERROR hibernate.AssertionFailure - an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
Message: null id in manytomany.Address entry (don't flush the Session after an exception occurs)
Line | Method
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 724 | run . . . in java.lang.Thread
| Error 2013-11-13 17:37:01,628 [localhost-startStop-1] ERROR context.GrailsContextLoader - Error initializing the application: null id in manytomany.Address entry (don't flush the Session after an exception occurs)
Message: null id in manytomany.Address entry (don't flush the Session after an exception occurs)
Line | Method
->> 334 | innerRun in java.util.concurrent.FutureTask$Sync
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 166 | run in java.util.concurrent.FutureTask
| 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor
| 615 | run in java.util.concurrent.ThreadPoolExecutor$Worker
^ 724 | run . . . in java.lang.Thread
【问题讨论】: