GWT Gilead 与 Hibernate 整合时异常处理
gwt与Hibernate整合会遇到集合序列化的问题,由于Hibernate内部用了代理集合类,所以会抛出org.hibernate.collection.PersistenceList不能被Gwt序列化的异常。
从网上找到谷歌的解决方案:http://code.google.com/intl/zh-CN/webtoolkit/articles/using_gwt_with_hibernate.html,使用Gilead来解决上述问题,但是却抛出如下异常:
java.lang.RuntimeException:java.lang.ClassCastException:java.util.HashMapcannotbecasttonet.sf.gilead.pojo.gwt.IGwtSerializableParameter
继续在网上搜寻答案,没找到解决方案,绝望ing。。。。
后来又到Gilead官网去看看,似乎有了点眉目,于是将Google的代码private HibernateUtil gileadHibernateUtil = new HibernateUtil(); /** * Constructor */ public MusicStoreServiceImpl() { gileadHibernateUtil.setSessionFactory(com.google.musicstore.util.HibernateUtil .getSessionFactory()); PersistentBeanManager persistentBeanManager = new PersistentBeanManager(); persistentBeanManager.setPersistenceUtil(gileadHibernateUtil); persistentBeanManager.setProxyStore(new StatelessProxyStore()); setBeanManager(persistentBeanManager); }稍加改动成如下代码:
private HibernateUtil gileadHibernateUtil = new HibernateUtil(); /** * Constructor */ public MusicStoreServiceImpl() { gileadHibernateUtil.setSessionFactory(com.google.musicstore.util.HibernateUtil .getSessionFactory()); //对于PersistentBeanManager, //需要使用GwtConfigurationHelper.initGwtStatelessBeanManager(gileadHibernateUtil) //这句话进行配置,而不是简单的new PersistentBeanManager persistentBeanManager = GwtConfigurationHelper.initGwtStatelessBeanManager(gileadHibernateUtil); // 下面注释掉的这句话不需要 // persistentBeanManager.setProxyStore(new StatelessProxyStore()); setBeanManager(persistentBeanManager); }在业务方法里这样写
public User validateUser(User user) {//在业务方法里这样写 Session session = gileadHibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction();//这里必须加事务,不加Gilead会抛异常 user = (User)session.createQuery("from User u where u.username=? and u.password=?") .setParameter(0, user.getUsername()) .setParameter(1, user.getPassword()) .uniqueResult(); session.getTransaction().commit(); return user; }
大功告成!再没有异常,成功将对象从Server端传到了Client端。