xNeyte xNeyte - 10 months ago 160
JSON Question

Hibernate and Jackson lazy serialization

I'm working on a project using Hibernate and Jackson to serialize my objects.
I think I understand how it is suposed to work but I can't manage to make it works.

If I understand well, as soon as a relation fetch mode is set to LAZY, if you want this relation, you have to initialize it.

Here is my class :

@JsonIgnoreProperties(ignoreUnknown = true)
@Table(schema="MDDI_ADMIN", name = "MINIUSINE")
public class MiniUsine {

@Column(name="MINIUSINEID", nullable = false)
private int miniUsineID;

@Column(name = "NAME", length = 40, nullable = false)
private String name;

@OneToMany(cascade = CascadeType.ALL)
private Set<Flux> fluxs = new HashSet<Flux>();

And all getters and setters.

I've also tried this
as class annotation. Also tried the NON_NULL.
However, jackson keeps sending me

com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: MiniUsine.fluxs, no session or session was closed (through reference chain: java.util.ArrayList[0]->MiniUsine["fluxs"])

I'm serializing it with :

Using Jackson 2.3.2

Thanks for help


As far as I understand, the entity object that hibernate returns is a proxy which derives from your entity class. If you try to access getter methods for lazy fields outside of a transaction, you get LazyInitializationException. The point I want to make is setting fluxs to empty set doesn't help you at all.

private Set<Flux> fluxs = new HashSet<Flux>();

Hibernate overloads the getter and if you try to access it outside of a transaction(which jackson is doing to check if it is empty), you get the LazyInit error.