【问题标题】:How to persist an entity which contains a field of user type using JPA2如何使用 JPA2 持久化包含用户类型字段的实体
【发布时间】:2011-01-30 08:00:24
【问题描述】:

我正在寻找一种方法来持久化包含用户类型字段的实体。 在这个特定示例中,我想将 ts 字段保留为毫秒数。

import org.joda.time.DateTime;

@Entity
public class Foo {

  @Id
  private Long id;

  private DateTime ts;
}

【问题讨论】:

    标签: java jpa jpa-2.0


    【解决方案1】:

    由于它不是 JPA 定义的受支持类型,因此您依赖于实现细节。 DataNucleus 有一个 JodaTime 插件,可以实现您想要的持久性。

    【讨论】:

      【解决方案2】:

      JPA 无法注册自定义属性类型,您必须使用提供者特定的东西:

      【讨论】:

      • 令人难以置信的是,他们没有像在 JAXB 中那样构建适配器:public class DateAdapter extends XmlAdapter{...
      【解决方案3】:

      您可以使用这些提供程序特定的东西,也可以使用 @PostPersist@PostUpdate@PostLoad 回调方法和代理 @Transient 字段。

      http://www.java2s.com/Tutorial/Java/0355__JPA/EntityListenerPostLoad.htm 会给你一些想法。

      如有任何进一步的说明,请随时与我们联系。

      【讨论】:

      【解决方案4】:

      一种解决方案是使用非列属性并用 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; }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-22
        • 1970-01-01
        • 2014-12-14
        • 2018-11-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多