mysql - Grails:向多对多关系添加值并将它们存储在数据库中
问题描述
我有两个班车辆和车库。
车辆是一种车辆(卡车,汽车,公共汽车......)
车库可以有许多类型的车辆。
一种车辆可能与许多车库相关联。
所以我可以检索所有具有车辆类型的车库,以及车库中的所有车辆类型。
Class Vehicule extends Content implements Serializable {
String type // PEUGEOT / BMW ...
static hasMany = [garages: Garage]
}
Class Garage extends Content implements Serializable {
static hasMany = [
vehicules: Vehicule,
users: User
]
}
在数据库中,我很好地创建了关联表。
在 Bootstrap.groovy 中,我预先填充了我的数据库。
def user1 = new User(...).save()
def garage1 = new Garage(...).save()
def garage2 = new Garage(...).save()
def garage3 = new Garage(...).save()
def vehicule1 = new Vehicule(...).save()
def vehicule2 = new Vehicule(...).save()
def vehicule3 = new Vehicule(...).save()
在这个阶段,一切正常!
事实上,我可以在我的 MySQL 数据库中看到“Vehicule”、“Garage”和“User”的所有实例。
------------------------问题在这里------------------------ -
仍然在Bootstrap.groovy中,我尝试在我的实例之间创建关系。
garage1.addToVehicules(vehicule1)
garage1.addToVehicules(vehicule2)
garage2.addToVehicules(vehicule1)
garage3.addToVehicules(vehicule1)
garage1.addToUsers(user1)
vehicule1.addToGarages(garage1)
vehicule1.addToGarages(garage2)
vehicule1.addToGarages(garage3)
...
然后,我保存它并设法意识到任何错误。
if (!garage1.save()) {
log.error garage1.errors.allErrors.join(' \n')
}
if (!garage2.save()) {
log.error garage2.errors.allErrors.join(' \n')
}
...
在编译和启动时,没有错误,没有堆栈跟踪。
但是当我访问我的 MySQL 数据库时,没有一个映射表被填满。(vehicule_garages为空,garage_vehicules为空,garage_users为空)
------------------------问题结束---------- --
我错过了什么?
代码中没有错误,保存了对象的实例,但没有关系。
提前致谢
解决方案
在多对多中,您可以使用像 GarageVehicule 这样的中间类
class GarageVehicule {
Vehicule vehicule
Garage garage
static belongsTo = [
vehicule: Vehicule,
garage: Garage
]
}
车库:
class Garage {
static hasMany = [
garageVehicules: GarageVehicule
]
}
车辆:
class Vehicule {
String type
static hasMany = [
garageVehicules: GarageVehicule
]
}
在 Boostrap 中:
def garage1 = new Garage().save(failOnError: true)
def vehicule1 = new Vehicule(type: 'BMW').save(failOnError: true)
new GarageVehicule(vehicule: vehicule1, garage: garage1).save(failOnError: true) // with failOnError you will see the errors if a domain has erros and you try to save it.
数据保存在 GarageVehicule 中。
推荐阅读
- angular - 在 Location.go() 之后,History.back() 不会触发 ActivatedRoute.paramMap
- kubernetes - 如何从春季启动到 Kubernetes 发出“坏”但不是“致命”的健康检查信号?
- python-3.7 - “元组”对象不可调用?
- javascript - 试图在反应中添加多张图片,但它只显示一张图片
- azure - 即使我使用了切换按钮并获得了用户和管理员的同意,也需要管理员同意警告
- python - TensorFlow - tensorflow.python.framework.errors_impl.FailedPreconditionError
- r - R quantmod:拉取数据时出现连接错误
- ssh - 将 Visual Studio Code (VSCode) 连接到 VirtualBox VM
- javascript - 拖拽逐渐变慢
- mysql - 通讯链路故障,Spring Boot + MySql +Docker + Hibernate