Friday, October 19, 2012

Custom templates for reverse engineering of hibernate tools

Recently I got a problem that when jersey converts java object to json it encountered this exception.

org.codehaus.jackson.map.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.ArrayList[46]->jobprep.domain.educationfacility.Director_$$_javassist_2["handler"])


The solution is here. After read this thread, I think it's better to add @JsonAutoDetect(value = JsonMethod.NONE) to each java entity class and @JsonProperty to each property. However I am using hiberate tools to generate java entity automatically so I need to find out how to add these annotations via the reverse engineering.

I found I can use hibernate tool reverse engineering custom templates to achieve this. But I found after I created a folder and copied all .ftl files from the POJO folder in hibernate-tools-x.x.x.jar, it still didn't work. After googling a while I got the final solution.

I need to also copy the DAO folder to the same level. Then it works.



Here is the content PojoTypeDeclaration.ftl which adds @JsonAutoDetect to class

/**
${pojo.getClassJavaDoc(pojo.getDeclarationName() + " generated by hbm2java", 0)}
 */
<#include "Ejb3TypeDeclaration.ftl"/>
@${pojo.importType("org.codehaus.jackson.annotate.JsonAutoDetect")}(value = ${pojo.importType("org.codehaus.jackson.annotate.JsonMethod")}.NONE)
${pojo.getClassModifiers()} ${pojo.getDeclarationType()} ${pojo.getDeclarationName()} ${pojo.getExtendsDeclaration()} ${pojo.getImplementsDeclaration()}

And PojoPropertyAccessors.ftl which adds JsonProperty

<#-- // Property accessors -->
<#foreach property in pojo.getAllPropertiesIterator()>
<#if pojo.getMetaAttribAsBool(property, "gen-property", true)>
 <#if pojo.hasFieldJavaDoc(property)>    
    /**       
     * ${pojo.getFieldJavaDoc(property, 4)}
     */
</#if>
    <#include "GetPropertyAnnotation.ftl"/>
    @${pojo.importType("org.codehaus.jackson.annotate.JsonProperty")}
    ${pojo.getPropertyGetModifiers(property)} ${pojo.getJavaTypeName(property, jdk5)} ${pojo.getGetterSignature(property)}() {
        return this.${property.name};
    }
    
    ${pojo.getPropertySetModifiers(property)} void set${pojo.getPropertyName(property)}(${pojo.getJavaTypeName(property, jdk5)} ${property.name}) {
        this.${property.name} = ${property.name};
    }
</#if>
</#foreach>




No comments:

Post a Comment