2017-10-11 146 views
-1

我有一个实体,我的文件系统链接是这样的:删除文件孤儿删除

@Entity 
public class MyDocument { 
    @Id 
    private Long documentId; 
    private String fileName; 
    private String filePath; 
    //Then a lot of other fields, getters and setters 
} 

如果我从数据库中删除文档(孤儿删除为例),我想删除在Async方法中的相应文件。

有什么建议吗?有没有办法拦截JPA删除操作?

回答

1

您应该查看实体的事件生命周期,特别是preRemove。

有了注解的配置是做

@PreRemove 
public void deleteFile(){ 
    //your async logic 
} 

编辑一样简单:你也可以创建一个这样的分离服务:

@Service 
public class FilerService { 
    @PostRemove 
    @Async 
    void deleteFile(MyDocument document) { 
     Files.deleteIfExists(Paths.get(document.getFilePath())); 
    } 
} 

而且随着@EntityListeners

@Entity 
@EntityListeners(FilerService.class) 
public class MyDocument { 
    @Id 
    private Long documentId; 
    private String fileName; 
    private String filePath; 
    //Then a lot of other fields, getters and setters 
} 
+0

由于其绑定!那是我正在寻找的。我在另一个服务中添加了这个拦截器:http://www.objectdb.com/java/jpa/persistence/event#Listeners_and_External_Callback_Methods_ –