[原创]利用Hibernate监听器,自动删除附件表对应的物理文件
问题的提出:
我们太懒了,通常从数据表中删除一条附件信息后,没有删除磁盘中对应的物理文件。
实现方案:
1、写一个标识接口,用来申明该实体关联有物理文件。
/** * @author Li Tonggang * 该接口通常被实体对象继承,标识对象与文件系统有关联, * 比如:附件对象 * 该接口通常和AttachDelListener协作删除文理文件。 */public interface FSEntitySupport {/** * @return 文件的绝对路径 */public String[] getFilePath();}/** * @author Li Tonggang * 删除附件对象时,自动删除与之关联的物理文件。 * 实体须实现接口 FSEntitySupport */public class AttachDelListener implements PostDeleteEventListener {public void onPostDelete(PostDeleteEvent arg0) {Object entity = arg0.getEntity();if(entity instanceof FSEntitySupport){FSEntitySupport fsEntity = (FSEntitySupport)entity;String[] pathArray = fsEntity.getFilePath();if(pathArray == null)return;for(String path : pathArray){File file = new File(path);if(file.exists())file.delete();}}}}<property name="eventListeners"> <map> <entry key="post-delete"> <bean class="common.hibernate.AttachDelListener"/> </entry> </map> </property>