Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey API + JPA/Hibernate Criteria Lazy Loading not working

Here is a simplified POJO i have:

@Entity
@Table( name = "Patient" )
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn
(
                name="Discriminator",
                discriminatorType=DiscriminatorType.STRING
                )
@DiscriminatorValue(value="P")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class Patient implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "ID", unique = true, nullable = false)
    protected Integer ID;

    @ManyToOne(targetEntity = TelephoneType.class, fetch=FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name="IDPhoneType")
    protected TelephoneType phoneType;


    @JsonProperty(required=false, value="phoneType")
    public TelephoneType getPhoneType() {
        return phoneType;
    }
    public void setPhoneType(TelephoneType phoneType) {
        this.phoneType = phoneType;
    }
}

Now here is my class TelephoneType:

@Entity
@Table( name = "TelephoneType" )
@Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
@JsonAutoDetect(getterVisibility=Visibility.NONE, isGetterVisibility=Visibility.NONE, fieldVisibility=Visibility.NONE)
public class TelephoneType implements Serializable{

private static final long serialVersionUID = -3125320613557609205L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "ID", unique = true, nullable = false)
private Integer ID;

@Column(name = "Name")
private String name;

@Column(name = "Description")
private String description;

public TelephoneType() {
}

@JsonProperty(value="id")
public int getID() {
    return ID;
}

public void setID(int iD) {
    ID = iD;
}

@JsonProperty(value="name")
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

@JsonProperty(value="description")
public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

}

The reason i use the @JsonAutoDetect annotation in TelephoneType is first to customize the json property names (i needed to deactivate the default jsonautodetect) and also because if I don't, I get an error when fetching the Queue

No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: my.package.Patient["phoneType"]->my.package.TelephoneType_$$_jvste17_13["handler"])

So without the @JsonAutoDetect annotation i get the error and with the annotation no Lazy Loading occurs and the TelephoneType is always loaded in the json response.

I use Criteria to make the query:

return this.entityManager.find(Patient.class, primaryKey);

I also added, as I read in different posts on so, the following in the web.xml of my application (Jersey API):

<filter>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>OpenEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Now somehow I surely missed something in my configuration but can't figure out what and we have many @ManyToOne relationships in the db that are slowing down the api considerably (some heavier objects than the one I showed in the example) so I would really appreciate to find a way to activate this lazy loading thing...

like image 900
jon Avatar asked May 06 '16 20:05

jon


People also ask

Does Hibernate support lazy loading?

Hibernate applies lazy loading approach on entities and associations by providing a proxy implementation of classes. Hibernate intercepts calls to an entity by substituting it with a proxy derived from an entity's class.

How does lazy loading work in JPA?

LAZY it is interpreted as a hint to the JPA provider that the loading of that field may be delayed until it is accessed for the first time: the property value in case of a @Basic annotation, the reference in case of a @ManyToOne or a @OneToOne annotation, or.

How set lazy load in Hibernate?

To enable lazy loading explicitly you must use “fetch = FetchType. LAZY” on an association that you want to lazy load when you are using hibernate annotations. @OneToMany( mappedBy = "category", fetch = FetchType.

How do you initialize a lazy load?

Implementing a Lazy-Initialized Property To implement a public property by using lazy initialization, define the backing field of the property as a Lazy<T>, and return the Value property from the get accessor of the property. The Value property is read-only; therefore, the property that exposes it has no set accessor.


2 Answers

If you are using JSON then I presume that you are supplying the results through a REST endpoint. What is happening then is you are passing the Patient entity back to the REST service. When the REST service, Jersey in this case, serializes the Patient entity it touches all of the properties, and even walks through them, so as to build as complete a tree as possible. In order to do this, every time Jersey hits a property that's not yet initialized, Hibernate makes another call back to the database. This is only possible if the EntityManager is not yet closed.

This is why you have to have the OpenEntityManagerInViewFilter installed. Without it, the EntityManager is closed when you exit the service layer and you get a LazyInitializationException. The OpenEntityManagerInViewFilter opens the EntityManager at the view level and keeps it open until the HTTP request is complete. So, while it seems like a fix, it's not really because, as you see, when you lose control over who is accessing the properties of your entities, in this case Jersey, then you end up loading things you didn't want to load.

It's better to remove the OpenEntityManagerInViewFilter and figure out what exactly you want Jersey to serialize. Once you have that figured out, there are at least two ways to go about handling it. IHMO, the "best practice" is to have DTO, or Data Transfer Objects. These are POJOs that are not entities but have pretty much the same fields. In the case, the PatientDTO would have everything except the phoneType property (or maybe just the Id). You would pass it a Patient in the constructor and it would copy the fields you want Jersey to serialize. Your service layer would then be responsible for returning DTO's instead of Entities, at least for the REST endpoints. Your clients would get JSON graphs that represent these DTOs, giving you better control over what goes into the JSON because you write the DTOs separate from the Entities.

Another option is to use JSON annotations to prevent Jersey from attempting to serialize properties you don't want serialized, such as phoneType, but that ultimately becomes problematic. There will be conflicting requirements and you never get it sorted out well.

While making DTO's at first seems like a horrible pain, it's not as bad as it seems and it even helps when you want to serialize values that are more client friendly. So, my recommendation is to lose the OpenEntityManagerInViewFilter and construct a proper service layer that returns DTOs, or View Objects as they are sometimes called.

References: What is Data Transfer Object?

REST API - DTOs or not?

Gson: How to exclude specific fields from Serialization without annotations

like image 189
K.Nicholas Avatar answered Oct 11 '22 02:10

K.Nicholas


To understand what is happening here you have to understand how lazy loading works in Hibernate.

When a list is declared as "lazy loaded" the Hibernate framework implements a "lazy loaded" JavassistLazyInitializer object with Javassist. Hence, the phoneType on your patient object is not an implementation of your TelephoneType class. It is a proxy towards it. When getPhoneType() on this object is called however, the proxy on patient is replaced by the real object. Unfortunately, @JsonAutoDetect uses reflection on the proxy object without ever calling getPhoneType() and tries to actually serialise the JavassistLazyInitializer object which of course is impossible.

I think the most elegant solution for this is to implement a query that fetches the patients with their telephoneType.

So instead of:

return this.entityManager.find(Patient.class, primaryKey);

Implement something like:

EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Patient> query = cb.createQuery(Patient.class);
Root<Patient> c = query.from(Patient.class);
query.select(c).distinct(true);
c.fetch("phoneType");
TypedQuery<Patient> typedQuery = em.createQuery(query);
List<Patient> allPatients = typedQuery.getResultList();

Adapting the query to your needs as required.

like image 45
Integrating Stuff Avatar answered Oct 11 '22 02:10

Integrating Stuff