HDa*_*ave 4 time types annotations jpa duration
我在一个类型的类中有一个属性字段javax.xml.datatype.Duration.它基本上代表一个时间跨度(例如4小时34分钟).
JPA告诉我这是一种无效的类型,这并不会让我感到震惊.
这是一个很好的解决方案吗?我可以实现自己的Duration类,但我不知道如何让JPA"接受"它作为数据类型.
这是一个很好的解决方案吗?我可以实现自己的Duration类,但我不知道如何让JPA"接受"它作为数据类型.
JPA不支持自定义类型,因此如果您想这样,您必须使用提供商提供的JPA扩展.例如,Hibernate允许定义您声明的自定义值类型@Type.显然,这会损害提供商之间的可移植性,这可能是一个问题.如果没有,那么你知道它是可行的.
使用标准JPA,传统方法是添加另一个getter/setter对,它可以调整有问题的属性并在访问时执行转换.我会用a Long来存储持续时间:
public MyEntity implements Serializable {
private Long id;
private javax.xml.datatype.Duration duration;
@Id
@GeneratedValue
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Transient
public Duration getDuration() {
return this.duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Long getDurationAsJpaCompatibleType() {
return MyXmlUtil.convertDurationToLong(this.duration);
}
public void setDurationAsJpaCompatibleType(Long duration) {
setDuration(MyXmlUtil.convertLongToDuration(duration));
}
}
Run Code Online (Sandbox Code Playgroud)