我必须从excel导入数据库。数据库的一部分看起来像:
class Network {
String externalId
String name
static hasMany = [phones: Phone]
static mapping = {
phones cascade: 'save-update,delete,all-delete-orphan'
}
}
class Phone{
String number
static belongsTo = [Network]
}
我还有一个定义excel记录的类:
class NetworkExcelRecord{
String externalId
String name
String phone1
String phone2
public def updateDomain() {
if (!externalId)
return null
Network instance = Network.findByExternalId(externalId) ?: new Network()
instance.properties = this.properties
if (instance.isDirty() || !instance.id)
instance.save(failOnError: true,flush: true)
}
private def getPhones() {
def phonesOld = Network.findByExternalId(externalId)?.phones
def phonesNew = []
(1..2).collect {this."phone$it"}.eachWithIndex {String phoneNumber, Integer index ->
if (phoneNumber) {
Phone phone = phonesOld.find {it.number == phoneNumber}
if (!phone)
phone = new Phone(number: phoneNumber)
phone.sortOrder = index
phone.save()
phonesNew << phone
}
}
phonesNew
}
}
但参考网络 - 电话已更新,但孤立的电话未被删除。有什么建议吗?
答案 0 :(得分:0)
尝试删除belongsTo
课程中的Phone
。通过在cascades
的映射中定义Network
,您不需要belongsTo
,因为它只定义了关系的保存 - 删除级联。