2

I want to load an objet and forget that it comes from hibernate! That's it, I just do something as:

MyClass myObject = MyClassDAO.getUnproxiedObject(objectID);

and than I have a real instance of myObj (and not from a Hibernate proxy) with all attributes set with the values from the database, so that I can't distinguish it from a manually created object.

In this thread a method is present to create an unproxied object, but it does not treats the issue of eager loding the objects, what I suppose is necessary for achieving my ultimate goals.

For those who are wondering why would I want such objects, I need to serialize then to Json with Gson, but I think it would have many other uses for many people.

Community
  • 1
  • 1
Saul Berardo
  • 2,530
  • 2
  • 18
  • 21

3 Answers3

0

Use FetchType.EAGER to eagerly load all the relations. Specifically for JSON serialization, if you are building a web application consider using an OpenSessionInView interceptor for your HTTP requests.

Satadru Biswas
  • 1,519
  • 1
  • 13
  • 23
0

after testing I found out that the method given in the citted post did exactly what I was looking for.

Saul Berardo
  • 2,530
  • 2
  • 18
  • 21
0

The reason hibernate doesn't de-proxy while rendering with GSON is that GSON uses reflection to serialize the fields rather than using the getters of the Hibernate object. To workaround, you need to register a new TypeHierarchyAdapter that will de-proxy the object as GSON is serializing.

Here's my approach:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer());
String jsonLove = gson.toJson(objToSerialize);

Here's the HibernateProxySerializer:

public class HibernateProxySerializer implements JsonSerializer<HibernateProxy> {

    @Override
    public JsonElement serialize(HibernateProxy proxyObj, Type arg1, JsonSerializationContext arg2) {
        try {
            GsonBuilder gsonBuilder = new GsonBuilder();
            //below ensures deep deproxied serialization
            gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer());
            Object deProxied = proxyObj.getHibernateLazyInitializer().getImplementation();
            return gsonBuilder.create().toJsonTree(deProxied);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
Frank Henard
  • 3,561
  • 3
  • 26
  • 40