主要包括兩個問題:
1、查詢結果轉換json時出現異常:
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不起作用了。當然這個註解不用加在每個實體上,寫一個接口去實現就行。
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer","fieldHandler"})
b.第二種方案,則是通過Hibernate4Module
添加依賴jar
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.9.8</version>
</dependency>
編寫類
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中
@Bean
public MappingJackson2HttpMessageConverter messageConverter(){
HibernateAwareObjectMapper hibernateAwareObjectMapper = new HibernateAwareObjectMapper();
MappingJackson2HttpMessageConverter HttpMessageConverter = new MappingJackson2HttpMessageConverter(hibernateAwareObjectMapper);
return HttpMessageConverter;
}
但是延遲加載的數據如何查詢出來,這就是第二個需要解決的問題了。
2、處理指定延遲對象加載方案:
@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();
}
}