我必须从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
}
}
但引用网络 - 电话会更新,但孤立电话不会被删除。有什么建议么?