It’s possible to use JsonIgnore when my lazily initialize is failed?

Tags: , ,

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)
@ManyToMany(targetEntity = Admin.class, fetch = FetchType.LAZY)
private Set<Admin> admins;

My Serializer:

class CustomSerializerAdmin extends StdSerializer<Set<Admin>> {
    public CustomSerializerAdmin() {

    public CustomSerializerAdmin(Class<Set<Admin>> admins) {

    public void serialize(Set<Admin> admins, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (!Hibernate.isInitialized(admins) | admins == null | admins.size() < 1) {
        } else {



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) {

Source: stackoverflow