有以下实体:
class Letter {
String email
String subject
String content
List attachments
static hasMany = [attachments : Attachment]
static constraints = {
subject nullable:true, blank:true
content nullable:true
email email:true
attachments nullable:true
}
和
class Attachment {
String fileName
Integer size
byte[] data
Letter letter
static belongsTo = [letter:Letter]
static constraints = {
fileName nullable: true, blank: true
size nullable: true, blank: true
data nullable: true, maxSize: 1024*1024*5 /*5MB*/
}
}
在单独的模块中创建一个字母,并将附件添加到此列表中。没有坚持。代码:
public Letter createLetterFromMessage(Message message) {
Letter letter = new Letter()
def addr = message.getFrom()[0]
if (addr instanceof InternetAddress) {
def inAddr = addr as InternetAddress
letter.email = inAddr.address
}
letter.subject = message.subject
def part = message as Part
letter.attachments = getAttachmetList(letter,part.getContent())//list of not persisted attaches
return letter
}
在另一个模块中,我需要保存已添加附件列表的信件。 代码:
public void onSuccess(List<Letter> letters) {
for (Letter letter : letters) {
if(letterService.save(letter)){
log.debug "Letter saved with id = ${letter.id}."
//do some work
} else
log.debug "Letter not saved and not added to execution context!"
}
}
怎么做?
文档中的示例在此处不起作用。
def book = new Book(title: 'Misery')
author.addToBooks(book)
author.save()
答案 0 :(得分:0)
我认为如果您只是将字母实例分配给每个附件的letter
属性,然后保存字母实例,它应该传播保存到每个附件:
letter.attachments.each{ it.letter = letter }
letter.save()
这基本上是addTo*
方法的作用
答案 1 :(得分:0)
这部分在createLetterFromMessage
:
....
def part = message as Part
letter.attachments = getAttachmetList(letter,part.getContent())//list of not persisted attaches
return letter
...
应该是
getAttachmetList(letter,part.getContent()).each { Attachment a ->
letter.addToAttachments(a)
}
然后你应该保存Letter实例,并且附件也将被保留。
否则应使用@injecteer建议