2

I use Spring JPA with hibernate,WebFlux and have problems with it. I've tried to fetch some entities from database, but lazy load exception occurred when i try to convert my entity to DTO. I understand why it happen and i can avoid it by creating DTO's per entity graph (to fetch only eager properties), but it's seem's to be overkill. Also i tried to skip lazy properties using setPropertyCondition() and Hibernate.isInitialized(), but exception was throwed before property condition was checked by model mapper. I tried to return entity object in my mapping but i couldn't find correct configuration for jackson Hibernate5Module usage. So, i ask you how i should use @EntityGraph with my repositories to have no errors in controller, ideally lazy-loaded properties should be null.

I solved the problem with lazy initialization exception by skipping lazy properties during DTO mapping process. I created own value reader for it and applied it to java model mapper instance.

public class CustomValueReader implements ValueReader<Object> {
    @Override
    public Object get(Object source, String memberName) {
        try {
            Field field = source.getClass().getDeclaredField(memberName);
            field.setAccessible(true);
            return field.get(source);
        }
        catch(Exception e) {
            return null;
        }
    }

    @Override
    public Member<Object> getMember(Object source, String memberName) {
        final Object value = get(source, memberName);
        Class<?> memberType = value != null ? value.getClass() : Object.class;
        return new Member<Object>(memberType) {
            @Override
            public Object getOrigin() {
                return null;
            }

            @Override
            public Object get(Object source, String memberName) {
                return CustomValueReader.this.get(source, memberName);
            }
        };
    }

    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public Collection<String> memberNames(Object source) {
        List<String> properties = new ArrayList<>();
        for (Field field : source.getClass().getDeclaredFields()) {
            field.setAccessible(true);//needed for accessing field using reflection
            boolean valid = true;
            Object fieldValue = null;
             try{
                 fieldValue = field.get(source);
             }
             catch(Exception e) {
                 valid = false;
             }
            boolean isInited = valid && Hibernate.isInitialized(fieldValue);
             if (isInited){
                 properties.add(field.getName());
             }
        }
        return properties;
    }

    @Override
    public String toString() {
        return "Costum";
    }
}

Apply it to mapper

mapper.getConfiguration().addValueReader(new CustomValueReader());

Also i noticed that usage of entity graph make all properties eager or lazy (depending on EntityGraph.EntityGraphType) ignoring attributeNodes. My class definition looks like

@NamedEntityGraphs({
        @NamedEntityGraph(name = ClinicVisit.CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT_AND_DEVICES,
                attributeNodes = @NamedAttributeNode(value = "patient",subgraph = "CVEG_DEVICES"),
                subgraphs = @NamedSubgraph(name = "CVEG_DEVICES", attributeNodes = @NamedAttributeNode("notificationDevices"))
        ),
        @NamedEntityGraph(name = ClinicVisit.CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT,
                attributeNodes = @NamedAttributeNode(value = "patient")
        )
})


@Entity
@Table(name="clinic_visit_request")
@Getter
@Setter
public class ClinicVisit {

    public final static String CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT_AND_DEVICES = "clinic_visit_request_patient_devices";
    public final static String CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT = "clinic_visit_request_patient";

    @Id
    @GeneratedValue
    protected Long id;

    @Column(name = "visit_date")
    protected Date visitDate;

    @Column(name = "update_date")
    protected Date updateDate;

    protected Boolean informed;

    @Column( columnDefinition = "boolean default false", nullable = false)
    protected Boolean handled = false;

    @ManyToOne()
    protected ClinicUser doctor;

    @ManyToOne()
    protected ClinicUser patient;

    @ManyToOne()
    protected ClinicUser confirmer;
}

My repository method definition:

@EntityGraph(value=ClinicVisit.CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT,type= EntityGraph.EntityGraphType.FETCH)
   List<ClinicVisit> findAll();

All works fine, it was my misunderstanding. I had three fields (doctor, patient, confirmer) and save same user in them, so when I added NamedAttributeNode for patient i expected that only patient will be loaded, but other fields were loaded because hibernate is clever.

I understand why Hibernate5Module wasn't working. I use WebFlux, so configuration for JacksonMapper should look like

@Configuration
public class AppConfig {

@Bean
Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
    return jacksonObjectMapperBuilder -> jacksonObjectMapperBuilder
            .featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
            .modules(new Hibernate5Module());
}


@Bean
Jackson2JsonEncoder jackson2JsonEncoder(ObjectMapper mapper){
    return new Jackson2JsonEncoder(mapper);
}

@Bean
Jackson2JsonDecoder jackson2JsonDecoder(ObjectMapper mapper){
    return new Jackson2JsonDecoder(mapper);
}

@Bean
WebFluxConfigurer webFluxConfigurer(Jackson2JsonEncoder encoder, Jackson2JsonDecoder decoder) {
    return new WebFluxConfigurer() {
        @Override
        public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
            configurer.defaultCodecs().jackson2JsonEncoder(encoder);
            configurer.defaultCodecs().jackson2JsonDecoder(decoder);
        }
    };
}

}

roma2341
  • 111
  • 2
  • 10

1 Answers1

0

Setting up Hibernate5Module is as easy as creating a bean:

@Bean
public com.fasterxml.jackson.databind.Module datatypeHibernateModule() {
    return new Hibernate5Module();
}

See https://stackoverflow.com/a/37840526/10609423

Works perfectly with Spring Boot 2.1.2. Would of made this a comment if I could.

abrandell
  • 63
  • 4