This question is about application design practice. I am thinking how to solve situation with pojo
and fields that in application exist in more data types.
In my pojo there is one Date
field. When creating this pojo by hand I set Date
, when I parse from XML I have to deal with String
representation and when make it persistent with JPA
it should be Timestamp
.
What is in general best practise in these situation? Should that pojo has this field in two data type representations (String
and Date
) or only in one general Date
and while parsing from String convert it into Date
from String
?
Question #2: how to convert this date value from String
to Date
- as static method in pojo class? On place it into some external utility class.
Edit #1: I use Builder
pattern for these pojo-s.
答案 0 :(得分:1)
我喜欢我的域类有丰富的Date - DateTime(joda)表示。 Joda提供了大量让你操纵日期的方法,所以这在我看来是最好的选择。当我必须将日期写入xml或数据库时,我将它们转换。
您正在使用Builder模式,因此您可以提供多种设置日期的方法。例如:
private DateTime createdOn;
...
public Builder createdOn(final DateTime createdOn) {
this.createdOn = createdOn;
return this;
}
public Builder createdOn(final String createdOn) {
this.createdOn = DateTime.parse(createdOn, dateTimeFormatter);
return this;
}
public Builder createdOn(final Date createdOn) {
this.createdOn = new DateTime(createdOn);
return this;
}
字符串和日期之间的转换只是一个简单的调用,所以我不认为它必须是单独的实用程序类。另一件事是格式化程序。它必须知道日期已写入String的格式。您可能在95%的情况下使用相同的格式,因此我将提取格式化程序。