Using transient for both Gson and Hibernate in the same file

912 views Asked by At

I have entity that I need some of the fields not to be persisted and some of the fields not to be serialized.

I am using the @Transient on some of the fields but when I want to mark transient for the Gson. The issue is that hibernate picks it up and also not persist it since its also a keyword in Hibernate .

I use Hibernate-jpa-2.1-api javax.persistence.Transient

I am trying prevent addresses from being serialized and getDefaultAddress should not be saved.

Code:

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

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

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

Any solution?

2

There are 2 answers

0
Darshan Patel On

You can use @Expose

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

In order to be able to work with this annotation,

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

Source : http://www.javacreed.com/gson-annotations-example/

0
kanaparthikiran On

I am using Play Framework's implementation of JPA, and Gson.

I got it working with JPA class as follows, which involved constructing the embedded object dynamically before marshalling to json, and no changes were required for the GSON builder, as modifying GSONBuilder will change the strategy globally for other classes as well.

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