我正在使用 Velocity 在我的项目中生成不同的工件,包括 Java Hibernate Entities。
这是我的模板示例:
#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
问题是生成的代码如下所示:
@Column
private String vendor;
@NotNull
@Column(unique=true)
private String name;
@Column
private Integer min_quantity;
@Column
private String description;
@Column
private Boolean active;
我尝试了建议的解决方案,在每行后添加##,但没有帮助。有没有办法强制 Velocity 保持模板中定义的空格?
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);