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);