关键问题:
当本地的数据库增删改成功,而远程数据库增删改失败的时候,我们就需要对其进行异常处理。我们需要将增删改的对象保存起来然后插入到本地的同步表当中,当远程数据库可访问的时候,然后再将本地同步表中的数据取出来,然后生成对应的Object对象,然后使用远程数据库的dao进行增删改,增删改之后再将本地数据库的同步表记录删除。
前提:然后我们创建一个Java Project来演示:
项目源代码:https://github.com/nuptboyzhb/JavaJsonObjectBean
/* * $filename: TestMain.java,v $ * $Date: 2013-11-28 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */ package edu.njupt.zhb; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONObject; /* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: [email protected] *2013-11-28 Nanjing,njupt,China */ public class TestMain { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BeanModel saveBeanModel = getInitBean(); String clazzType = saveBeanModel.getClass().getName(); String jsonString = JSONObject.fromObject(saveBeanModel).toString(); printObject(saveBeanModel);//先打印一下看看 ////////////////我们可以通过clazzType和jsonString,在程序中重新生成saveBeanModel对象 JSONObject jsonObject = JSONObject.fromObject(jsonString); try { Object object = JSONObject.toBean(jsonObject, Class.forName(clazzType)); /////////////////////此时的object就是我们由clazzType和jsonString两个属性恢复出的对象 printObject(object); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static BeanModel getInitBean(){ List<BeanModel> list = new ArrayList<BeanModel>(); for(int i = 0;i<10;i++){ BeanModel beanModel = new BeanModel(); beanModel.setDate(new java.util.Date()); beanModel.setId(i); beanModel.setName("name"+i); } BeanModel saveBeanModel = new BeanModel(); saveBeanModel.setId(11); saveBeanModel.setDate(new java.util.Date()); saveBeanModel.setName("saveBean"); saveBeanModel.setList(list); return saveBeanModel; } public static void printObject(Object object){ String result = JSONObject.fromObject(object).toString(); System.out.println("结果:"+result); } }
/* * $filename: BeanModel.java,v $ * $Date: 2013-11-28 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */ package edu.njupt.zhb; import java.util.Date; import java.util.List; /* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: [email protected] *2013-11-28 Nanjing,njupt,China */ public class BeanModel { private Integer id; private Date date; private String name; private List<BeanModel> list; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<BeanModel> getList() { return list; } public void setList(List<BeanModel> list) { this.list = list; } }
注意:对于我们“恢复”的对象,我们可以使用Hibernate的getCurrentSession进行保存操作。但是,如果使用getCurrentSession来更新或删除这个对象,那么Hibernate就会报错。此时,我们需要使用Hibernate的sessionFactory.openSession方法,获得Session,然后再执行更新或者删除操作。