@ Programmatic public Paperclip attach ( final DocumentAbstract documentAbstract , final String roleName , final Object attachTo ) { Paperclip paperclip = findByDocumentAndAttachedToAndRoleName ( documentAbstract , attachTo , roleName ) ; if ( paperclip != null ) { return paperclip ; } final Class < ? extends Paperclip > subtype = subtypeClassFor ( attachTo ) ; paperclip = repositoryService . instantiate ( subtype ) ; paperclip . setDocument ( documentAbstract ) ; paperclip . setRoleName ( roleName ) ; if ( documentAbstract instanceof Document ) { final Document document = ( Document ) documentAbstract ; paperclip . setDocumentCreatedAt ( document . getCreatedAt ( ) ) ; } if ( ! repositoryService . isPersistent ( attachTo ) ) { transactionService . flushTransaction ( ) ; } final Bookmark bookmark = bookmarkService . bookmarkFor ( attachTo ) ; paperclip . setAttachedTo ( attachTo ) ; paperclip . setAttachedToStr ( bookmark . toString ( ) ) ; repositoryService . persistAndFlush ( paperclip ) ; return paperclip ; }
This is an idempotent operation .