hibernatereverse-engineeringfreemarkerhibernate-tools

Add properties to getter-annotations in Freemarker reverse engineering templates?



I am trying to implement a FreeMarker custom reverse engineering template that automatically creates my Hibernate classes.
In the build process, the template is used by hibernate-tools to generate the hibernate classes.
So far, I am using the default freemarker templates for that purpose and it works fine.

But now I am facing the questing:
How do I add additional properties to the default getter-annotations?

The default freemarker method for One-to-may associations is (implemented in Ejb3PropertyGetAnnotation.ftl):

...
<#elseif c2h.isCollection(property)>
    ${pojo.generateCollectionAnnotation(property, cfg)}
...

The generated java code is for example:

@OneToMany(fetch=FetchType.LAZY, mappedBy="person")      
public Set<ContactInformation> getContactInformations() {
    return this.contactInformations;
}

But I want to add cascade = CascadeType.ALL to each one-to-many getter annotation like this:

@OneToMany(cascade = CascadeType.ALL
           fetch=FetchType.LAZY, mappedBy="person")

I am new to freemarker and hibernate and have no idea how to archive this.

Thanks a lot for your help!


Solution

  • The answer is more simple: Just put ${property.setCascade("ALL")} before generateCollectionAnnotation method call.

    <#elseif c2h.isCollection(property)>
    ${property.setCascade("ALL")}
    ${pojo.generateCollectionAnnotation(property, cfg)}
    

    Also the result is much better because it uses the javax.persistence.CascadeType enum.

    @OneToMany(cascade = CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="person")
    public Set<ContactInformation> getContactInformations() {
    

    List of cascade types can be used:

    ${property.setCascade("persist, merge, delete, refresh")}
    

    The result:

    @OneToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.REFRESH }, fetch=FetchType.LAZY, mappedBy="person") 
    public Set<ContactInformation> getContactInformations() {
    

    This solution also generate the cascade type for ManyToMany relation. You need to control that if you don't like this behavior. The @OneToMany orphanRemoval attribute can be generate, but is out of the scope of the question.

    Kind regards.