【发布时间】:2011-01-30 08:00:24
【问题描述】:
我正在寻找一种方法来持久化包含用户类型字段的实体。 在这个特定示例中,我想将 ts 字段保留为毫秒数。
import org.joda.time.DateTime;
@Entity
public class Foo {
@Id
private Long id;
private DateTime ts;
}
【问题讨论】:
我正在寻找一种方法来持久化包含用户类型字段的实体。 在这个特定示例中,我想将 ts 字段保留为毫秒数。
import org.joda.time.DateTime;
@Entity
public class Foo {
@Id
private Long id;
private DateTime ts;
}
【问题讨论】:
由于它不是 JPA 定义的受支持类型,因此您依赖于实现细节。 DataNucleus 有一个 JodaTime 插件,可以实现您想要的持久性。
【讨论】:
JPA 无法注册自定义属性类型,您必须使用提供者特定的东西:
【讨论】:
您可以使用这些提供程序特定的东西,也可以使用 @PostPersist、@PostUpdate、@PostLoad 回调方法和代理 @Transient 字段。
http://www.java2s.com/Tutorial/Java/0355__JPA/EntityListenerPostLoad.htm 会给你一些想法。
如有任何进一步的说明,请随时与我们联系。
【讨论】:
@LOB [java2s.com/Tutorial/Java/0355__JPA/MarkStringAsLob.htm]
一种解决方案是使用非列属性并用 getter/setter 封装它们。
要告诉 JPA 使用 getter/setter 而不是直接访问私有字段,您必须在 public Long getId() 而不是 private Long id 上注释 @Id。执行此操作时,请记住对每个不直接对应于列的 getter 使用 @Transient。
以下示例将创建一个名为 myDate 的 Date 列,而应用程序将提供 DateTime getTs() 和 setTs() 方法。 (不确定 DateTime API,所以请原谅小错误:))
import org.joda.time.DateTime;
@Entity
public class Foo {
private Long id;
private DateTime ts;
@Id
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
// These should be accessed only by JPA, not by your application;
// hence they are marked as protected
protected Date getMyDate() { return ts == null ? null : ts.toDate(); }
protected void setMyDate(Date myDate) {
ts = myDate == null ? null : new DateTime(myDate);
}
// These are to be used by your application, but not by JPA;
// hence the getter is transient (if it's not, JPA will
// try to create a column for it)
@Transient
public DateTime getTs() { return ts; }
public void setTs(DateTime ts) { this.ts = ts; }
}
【讨论】: