I am using Velocity to generate different artifacts in my project, including Java Hibernate Entities.
Here is an example of my template:
#foreach( $column in $columns )
#if ($column.columnID != "id")
#if ($column.isColumnAnIdentifier)
@Id
#end
#if ($column.isColumnValueGenerated)
@GeneratedValue
#end
#if ($column.isColumnValueNotNull)
@NotNull
#end
#if ($column.columnAllowedValues)
@Enumerated(EnumType.STRING)
#end
#if ($column.isColumnValueUnique)
@Column(unique=true)
#elseif ($column.isColumnJoinedManyToOne)
@ManyToOne
@JoinColumn(name = "$column.columnJoinByID")
#else
@Column
#end
private #if ($column.columnAllowedValues) $column.columnID.toUpperCase() #else $column.columnType #end $column.columnID;
#end
#end
The problem is that the generated code looks like this:
@Column
private String vendor;
@NotNull
@Column(unique=true)
private String name;
@Column
private Integer min_quantity;
@Column
private String description;
@Column
private Boolean active;
I tried the suggested solution with adding ## after each line, it does not help. Is there a way to force Velocity to keep whitespace as defined in the template?
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RESOURCE_LOADER_PROPERTY, RESOURCE_LOADER_VALUE);
velocityEngine.setProperty(CLASSPATH_RESOURCE_LOADER_PROPERTY, ClasspathResourceLoader.class.getName());
velocityEngine.init();
Template velocityTemplate = velocityEngine.getTemplate(TEMPLATE_RESOURCES_ROOT_FOLDER + "/" + templateFileName);;
StringWriter writer = new StringWriter();
velocityTemplate.merge(velocityContext, writer);
writeToFile(writer, destinationFilePath);
The ##
at the end of lines is not enough, you also need to remove the Velocity indentation.
An alternative, to keep the indentation, is to indent with Velocity comments:
#foreach( $column in $columns )##
#**##if ($column.columnID != "id")##
#* *##if ($column.isColumnAnIdentifier)##
@Id
#* *##end
#* *##if ($column.isColumnValueGenerated)##
...
but I concede it is rather ugly.
The upcoming Velocity 2.0 release adds a space gobbling option, active by default, with does exactly what you want. The latest release candidate is available here.