Springboot与Jpa整合问题

2019-08-07 11:55:02 浏览数 (1)

主要包括两个问题:

1、查询结果转换json时出现异常:

代码语言:javascript复制
Could not write JSON: No serializer found for class
 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to 
create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); 
nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for 
class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to 
create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) 
(through reference chain: 
xxxx->xxxx->java.util.Collections$UnmodifiableRandomAccessList[0]->xxxxx["xxxxx"]->xxxxx_$$_jvst928_69["handler"])"

其实解决这种问题有几种方案,目前说两种:

a.在实体类上加上注解,但是会导致新的问题,那就是关联的对象加上FetchType.LAZY不起作用了。当然这个注解不用加在每个实体上,写一个接口去实现就行。

代码语言:javascript复制
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer","fieldHandler"})

b.第二种方案,则是通过Hibernate4Module

添加依赖jar

代码语言:javascript复制
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate4</artifactId>
    <version>2.9.8</version>
</dependency>

编写类

代码语言:javascript复制
public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper(){
        Hibernate4Module hibernate4Module = new Hibernate4Module();
        hibernate4Module.configure(Hibernate4Module.Feature.USE_TRANSIENT_ANNOTATION, false);
        registerModule(hibernate4Module);
    }

    public void setPrettyPrint(boolean prettyPrint) {
        configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
    }
}

添加到MessageConverter中

代码语言:javascript复制
@Bean
public MappingJackson2HttpMessageConverter messageConverter(){
    HibernateAwareObjectMapper hibernateAwareObjectMapper = new HibernateAwareObjectMapper();
    MappingJackson2HttpMessageConverter HttpMessageConverter = new MappingJackson2HttpMessageConverter(hibernateAwareObjectMapper);
    return HttpMessageConverter;
}

但是延迟加载的数据如何查询出来,这就是第二个需要解决的问题了。

2、处理指定延迟对象加载方案:

代码语言:javascript复制
@Override
public T getOne(Serializable id, String[] props) {
    T t = repository.findOne(id);
    getRelationObj(t, props);
    return t;
}

private void getRelationObj(T initializeObject, String[] props) {
    if(props!=null){
        for(String prop : props){
            getRelationObj(initializeObject, prop);
        }
    }
}

private void getRelationObj(T initializeObject, String prop) {
    try {
        if(StringUtils.isNotEmpty(prop)){
            Object obj = PropertyUtils.getProperty(initializeObject, prop);
            Hibernate.initialize(obj);
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}

0 人点赞