我使用Spring JPA和hibernate,WebFlux并且遇到问题。我试图从数据库中获取一些实体,但是当我尝试将我的实体转换为DTO时发生了延迟加载异常。我理解它为什么会发生,我可以通过创建DTO的每个实体图(仅获取渴望的属性)来避免它,但它似乎是过度杀伤。此外,我试图使用setPropertyCondition()
和Hibernate.isInitialized()
跳过延迟属性,但在模型映射器检查属性条件之前抛出了异常。我试图在我的映射中返回实体对象,但我找不到jackson Hibernate5Module用法的正确配置。所以,我问你应该如何使用@EntityGraph
和我的存储库在控制器中没有错误,理想情况下,延迟加载的属性应为null。
我通过在DTO映射过程中跳过延迟属性来解决延迟初始化异常的问题。我为它创建了自己的值阅读器并将其应用于java模型映射器实例。
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";
}
}
将其应用于mapper
mapper.getConfiguration().addValueReader(new CustomValueReader());
此外,我注意到实体图的使用使所有属性变得急切或懒惰(取决于EntityGraph.EntityGraphType)忽略attributeNodes。我的班级定义看起来像
@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;
}
我的存储库方法定义:
@EntityGraph(value=ClinicVisit.CLINIC_VISIT_ENTITY_GRAPH_WITH_PATIENT,type= EntityGraph.EntityGraphType.FETCH)
List<ClinicVisit> findAll();
一切正常,这是我的误解。我有三个字段(医生,病人,确认者)并在其中保存相同的用户,所以当我为患者添加NamedAttributeNode时,我预计只会加载患者,但由于休眠是聪明的,因此加载了其他字段。
我理解为什么Hibernate5Module无法正常工作。我使用WebFlux,因此JacksonMapper的配置应该是这样的
@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);
}
};
}
}
设置Hibernate5Module就像创建bean一样简单:
@Bean
public com.fasterxml.jackson.databind.Module datatypeHibernateModule() {
return new Hibernate5Module();
}
见https://stackoverflow.com/a/37840526/10609423
与Spring Boot 2.1.2完美配合。如果可以的话,会不会发表评论。