【发布时间】:2023-02-03 05:52:23
【问题描述】:
我的实体包含一个 timestamp 属性,该属性正在转换为 LocalDateTime 作为 the docs specify。但是,我想将timestamp 转换为OffsetDateTime。有没有办法覆盖默认的转换行为?
This question 提到了一个 .dbrep,但我的项目中没有这样的文件。
【问题讨论】:
-
“.dbrep”是旧模型文件格式,自版本 4 后不再存在
我的实体包含一个 timestamp 属性,该属性正在转换为 LocalDateTime 作为 the docs specify。但是,我想将timestamp 转换为OffsetDateTime。有没有办法覆盖默认的转换行为?
This question 提到了一个 .dbrep,但我的项目中没有这样的文件。
【问题讨论】:
您无法覆盖默认的转换行为,
但您可以使用 Velocity 语言更改模板(.vm 文件)中的类型。
#if ( $attribute.neutralType == '时间戳' )
#set ($mytype = 'OffsetDateTime')
#别的
#set ($mytype = $attribute.simpleType )
#结尾如果必须在多个模板中重复此操作,您可以定义一个宏
- 如果您只想对某些属性强制转换:
- 在模型 (".entity") 中为相关属性添加标签:
我的字段:时间戳{#目标类型(偏移日期时间) } ;
- 在模板中使用这个标签值(并保持标准类型为默认值)
$attribute.tagValue('目标类型', $attribute.simpleType )
在这两种情况下,不要忘记导入 'java.time.OffsetDateTime'
【讨论】:
对于将来看到这里的任何人,我最终选择了@Igu 建议的答案(#1)——这不一定适用于所有实体的所有属性。 (除非我错过了它应该如何应用)。
宏看起来像:
#macro( typeFor $attribute )
#if ( $attribute.neutralType == 'timestamp' )OffsetDateTime#else$attribute.simpleType#end
#end
不幸的是,为了不在生成的.java 文件中添加额外的换行符或空格,格式化似乎是必要的。我将这个宏定义添加到一个通用的 #parse 文件中,并且能够在类似的模型和 DTO 中使用它。
调用宏如下所示:
#foreach( $attribute in $entity.nonKeyAttributes )
$jpa.fieldAnnotations(2, $attribute)
private #typeFor( $attribute ) $attribute.name#if($attribute.hasInitialValue()) = ${attribute.initialValue}#end;
#end
【讨论】: