我正在寻找一种方法来持久化包含用户类型字段的实体。在这个特定示例中,我想将ts字段保留为毫秒数。
import org.joda.time.DateTime;
@Entity
public class Foo {
@Id
private Long id;
private DateTime ts;
}
JPA 无法注册自定义属性类型,您必须使用提供者特定的东西:
由于它不是 JPA 定义的受支持类型,因此您依赖于实现细节。DataNucleus 有一个 JodaTime 插件,可以实现您想要的持久性。
您可以使用这些提供者特定的东西,也可以使用@PostPersist
带有代理 字段@PostUpdate
的回调方法。@PostLoad
@Transient
http://www.java2s.com/Tutorial/Java/0355__JPA/EntityListenerPostLoad.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; }
}