【问题标题】:Using transient for both Gson and Hibernate in the same file在同一个文件中对 Gson 和 Hibernate 使用瞬态
【发布时间】:2015-08-29 19:08:40
【问题描述】:

我有一个实体,我需要一些不被持久化的字段和一些不被序列化的字段。

我在某些字段上使用@Transient,但是当我想为 Gson 标记瞬态时。问题是hibernate会选择它并且也不会持久化它,因为它也是Hibernate中的一个关键字。

我使用 Hibernate-jpa-2.1-api javax.persistence.Transient

我正在尝试防止addresses 被序列化,并且不应保存getDefaultAddress

代码:

@Entity
@Table(name="Business")
public class Business{

    @OneToMany(mappedBy="business")
    private transient List<Phone> addresses;

    @Transient
    public Phone getDefaultPhone() {
        return phones.get(0);
    }
}

有什么办法吗?

【问题讨论】:

    标签: java hibernate gson transient


    【解决方案1】:

    你可以使用@Expose

    @Expose(serialize = false)
    @OneToMany(cascade=CascadeType.ALL, mappedBy="business")
    private List<Address> addresses;
    

    为了能够使用此注释,

    final GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    final Gson gson = builder.create();
    

    来源:http://www.javacreed.com/gson-annotations-example/

    【讨论】:

      【解决方案2】:

      我正在使用 Play Framework 的 JPA 和 Gson 实现。

      我让它与 JPA 类一起工作,如下所示,其中涉及在编组为 json 之前动态构造嵌入式对象,并且不需要对 GSON 构建器进行任何更改,因为修改 GSONBuilder 也会全局更改其他类的策略。

      public class DBServiceDefinition {
          @Transient
          @Expose(serialize = true)
          @SerializedName("serviceStatus")
          public ServiceDefinitionStatus status = new 
           ServiceDefinitionStatus(201,"SUCCESS","","Test");
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-08
        • 1970-01-01
        • 2021-09-21
        • 1970-01-01
        • 2012-01-25
        • 2013-01-06
        • 2013-03-31
        • 2022-01-02
        • 2011-06-14
        相关资源
        最近更新 更多