I search one way to use JsonIgnore (or just return an empty array) when my assotiation variable with fetch = FetchType.LAZY
isn’t initialize and use my own serializer when it is.
I tryed to do test in my serializer but I get the same error.
Thank you in advance!
My object:
@JsonSerialize(using = CustomSerializerAdmin.class) @Cascade(...) @ManyToMany(targetEntity = Admin.class, fetch = FetchType.LAZY) @JoinTable(...) private Set<Admin> admins;
My Serializer:
class CustomSerializerAdmin extends StdSerializer<Set<Admin>> { public CustomSerializerAdmin() { this(null); } public CustomSerializerAdmin(Class<Set<Admin>> admins) { super(admins); } @Override public void serialize(Set<Admin> admins, JsonGenerator gen, SerializerProvider provider) throws IOException { if (!Hibernate.isInitialized(admins) | admins == null | admins.size() < 1) { gen.writeString("[]"); } else { gen.writeString("[test]"); } } }
Advertisement
Answer
The |
operator in Java does not short-circuit, so you will call size()
anyway which triggers lazy initialization. You should use the double pipe ||
which short-circuits:
if (admins == null || !Hibernate.isInitialized(admins) || admins.size() < 1) {