[jboss-user] [JBossWS] - Re: avoid lazy-initialization exceptions

florian79 do-not-reply at jboss.com
Fri Jul 18 10:56:14 EDT 2008


another "ugly" solution is the following:

instad of 

  | @XmlIDREF
  | 
use:

  | @XmlJavaTypeAdapter(Entity2StringXMLAdapter.class)
  | 
 and here is the implementation for the Adapter:

  | public class Entity2StringXMLAdapter extends XmlAdapter<String,BasicEntity>
  | {
  | 
  | 	@Override
  | 	public String marshal(final BasicEntity entityGot) throws Exception
  | 	{
  | 
  | 		String strValue = "";
  | 		try
  | 		{
  | 			strValue = entityGot.getName() + "(" + entityGot.getId() + ")";
  | 		}
  | 		catch (LazyInitializationException e)
  | 		{
  | 			Long id = this.getEntityID(entityGot);
  | 			if(id == null)
  | 				id = new Long(-1);
  | 			strValue = "lazy (" + id + ")";
  | 
  | 		}
  | 		return strValue;
  | 	}
  | 
  | @Override
  | 	public BasicEntity unmarshal(final String arg0) throws Exception
  | 	{
  | 		return null;
  | 	}
  | 
  | 	private Long getEntityID(final BasicEntity entityGot)
  | 	{
  | 		//dirty, but it works:
  | 		//long duration = System.currentTimeMillis();
  | 		Long entityId = null;
  | 		Class clazz = entityGot.getClass();
  | 		for(Field fieldHandler : clazz.getDeclaredFields())
  | 		{
  | 			if(fieldHandler.getType().isAssignableFrom(javassist.util.proxy.MethodHandler.class) && fieldHandler.getName().equals("handler"))
  | 			{
  | 				try
  | 				{
  | 					fieldHandler.setAccessible(true);
  | 					javassist.util.proxy.MethodHandler methodHandler = (javassist.util.proxy.MethodHandler) fieldHandler.get(entityGot);
  | 
  | 					Field fieldID = AbstractLazyInitializer.class.getDeclaredField("id");
  | 					fieldID.setAccessible(true);
  | 					entityId = (Long)fieldID.get(methodHandler);
  | 				}
  | 				catch (SecurityException e1)
  | 				{
  | 					e1.printStackTrace();
  | 				}
  | 				catch (IllegalArgumentException e1)
  | 				{
  | 					e1.printStackTrace();
  | 				}
  | 				catch (IllegalAccessException e1)
  | 				{
  | 					e1.printStackTrace();
  | 				}
  | 				catch (NoSuchFieldException e1)
  | 				{
  | 					System.out.println("======= THIS EXCEPTION DEPENDS ON A NEWER HIBERNATE VERSION!!!!!! ========");
  | 					e1.printStackTrace();
  | 				}
  | 				break;
  | 			}
  | 		}
  | 		return entityId;
  | 	}
  | }
  | 

BasicEntity is just Interface that is implemented by all my entities with the following methods:


  | public Long getId();
  | public void setId(final Long idGot);
  | public String getName();
  | public void setName(final String strNameGot);
  | 

View the original post : http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4165354#4165354

Reply to the post : http://www.jboss.com/index.html?module=bb&op=posting&mode=reply&p=4165354



More information about the jboss-user mailing list