簡體   English   中英

如何使用JPA2持久保存包含用戶類型字段的實體

[英]How to persist an entity which contains a field of user type using JPA2

我正在尋找一種方法來持久化包含用戶類型字段的實體。 在這個特定的例子中,我想將ts字段保持為毫秒數。

import org.joda.time.DateTime;

@Entity
public class Foo {

  @Id
  private Long id;

  private DateTime ts;
}

JPA無法注冊自定義屬性類型,您必須使用提供程序特定的東西:

一種解決方案是使用非列屬性並使用getter / setter封裝它們。

要告訴JPA使用getter / setter而不是直接訪問私有字段,您必須在公共Long getId()而不是私有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; }
}

由於它不是JPA定義的受支持類型,因此您依賴於實現細節。 DataNucleus有一個JodaTime插件,可以提供你想要的持久性。

要么你可以使用這些供應商特定的東西,或者你可以使用@PostPersist@PostUpdate@PostLoad回調方法與替代@Transient場。

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

如果需要進一步說明,請與我們聯系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM