How to pass entities mapped with hibernate to JSON?

0

I am commenting I am working with hibernate, then I show an entity product of the mapping:

public class Usuario implements java.io.Serializable {

    private String idUsuario;
    private Trabajador trabajador;  //one to one
    private String usu;
    private byte[] clave;
    private boolean estado;
    private boolean acceder;
    private Set<Acceso> accesos = new HashSet<Acceso>(0);  //one to many

    public Usuario() {
    }

    public Usuario(Trabajador trabajador, String usu, byte[] clave, boolean estado, boolean acceder) {
        this.trabajador = trabajador;
        this.usu = usu;
        this.clave = clave;
        this.estado = estado;
        this.acceder = acceder;
    }

    public Usuario(Trabajador trabajador, String usu, byte[] clave, boolean estado, boolean acceder, Set<Acceso> accesos) {
        this.trabajador = trabajador;
        this.usu = usu;
        this.clave = clave;
        this.estado = estado;
        this.acceder = acceder;
        this.accesos = accesos;
    }

    @GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "trabajador"))
    @Id
    @GeneratedValue(generator = "generator")

    @Column(name = "ID_USUARIO", unique = true, nullable = false, length = 15)
    public String getIdUsuario() {
        return this.idUsuario;
    }

    public void setIdUsuario(String idUsuario) {
        this.idUsuario = idUsuario;
    }

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn
    public Trabajador getTrabajador() {
        return this.trabajador;
    }

    public void setTrabajador(Trabajador trabajador) {
        this.trabajador = trabajador;
    }

    @Column(name = "USU", nullable = false, length = 12)
    public String getUsu() {
        return this.usu;
    }

    public void setUsu(String usu) {
        this.usu = usu;
    }

    @Column(name = "CLAVE", nullable = false)
    @ColumnTransformer(write = "ENCRYPTBYPASSPHRASE('frase',?)", read = "DECRYPTBYPASSPHRASE('frase',CLAVE)")
    public byte[] getClave() {
        return this.clave;
    }

    public void setClave(byte[] clave) {
        this.clave = clave;
    }

    @Column(name = "ESTADO", nullable = false)
    public boolean isEstado() {
        return this.estado;
    }

    public void setEstado(boolean estado) {
        this.estado = estado;
    }

    @Column(name = "ACCEDER", nullable = false)
    public boolean isAcceder() {
        return this.acceder;
    }

    public void setAcceder(boolean acceder) {
        this.acceder = acceder;
    }

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "usuario")
    public Set<Acceso> getAccesos() {
        return this.accesos;
    }

    public void setAccesos(Set<Acceso> accesos) {
        this.accesos = accesos;
    }

}

Before using hibernate, I passed my pojos to json and it worked fine now that I use hibernate to map the tables I get different errors.

Servlet.service() for servlet CLogin threw exception
java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:64)
    at com.google.gson.internal.bind.TypeAdapters$1.write(TypeAdapters.java:61)

add the class

public class HibernateProxyTypeAdapter extends TypeAdapter<HibernateProxy> {

    public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() {
        @Override
        @SuppressWarnings("unchecked")
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
            return (HibernateProxy.class.isAssignableFrom(type.getRawType())
                    ? (TypeAdapter<T>) new HibernateProxyTypeAdapter(gson) : null);
        }
    };
    private final Gson context;

    HibernateProxyTypeAdapter(Gson context) {
        this.context = context;
    }

    @Override
    public HibernateProxy read(JsonReader in) throws IOException {
        throw new UnsupportedOperationException("Not supported");
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Override
    public void write(JsonWriter out, HibernateProxy value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }
        // Retrieve the original (not proxy) class
        Class<?> baseType = Hibernate.getClass(value);
        // Get the TypeAdapter of the original class, to delegate the serialization
        TypeAdapter delegate = context.getAdapter(TypeToken.get(baseType));
        // Get a filled instance of the original class
        Object unproxiedValue = ((HibernateProxy) value).getHibernateLazyInitializer().getImplementation();
        // Serialize the value
        delegate.write(out, unproxiedValue);
    }

}

adding my gson

new GsonBuilder().registerTypeAdapterFactory(HibernateProxyTypeAdapter.FACTORY);

and when using gson:

System.out.println(Constante.gson.toJson(usuario));

I got the following error:

Servlet.service() for servlet CLogin threw exception
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164)
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)

initialize each entity

Hibernate.initialize(usuario.getTrabajador());
Hibernate.initialize(usuario.getAccesos());

but I still get error:

Servlet.service() for servlet CLogin threw exception
org.hibernate.HibernateException: collection is not associated with any session
    at org.hibernate.collection.internal.AbstractPersistentCollection.forceInitialization(AbstractPersistentCollection.java:663)
    at org.hibernate.Hibernate.initialize(Hibernate.java:78)

I have already googled but I can not find the solution, what can I do?

    
asked by Oscar 14.06.2018 в 23:28
source

0 answers