adramazany
adramazany

Reputation: 674

hibernate force fetching lazy field when needed

I have an entity with field related to another object that marked lazy

    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "fk_prs_insured")
    public Person getInsured() {
        return insured;
    }

but in jsp file when it referenced to fill an input, input showed nothing. how can I force to fetch this field where needed?

thanks,

Upvotes: 2

Views: 1513

Answers (1)

Alan Hay
Alan Hay

Reputation: 23246

Easiest thing to do is to remove the Lazy property from the @ManyToOne which are normally eager by default, unlike @OneToMany which are normally lazy.

You may of course have reason to avoid eagerly fetching by default in this case and therefore you could also enable Eager fetching for this particular use case by specifiying a fetch hint your query which loads the Entity for this particular use case.

See 15.5

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querycriteria.html

One problem with approach is that you can end up with various methods in you code such as loadCustomer(), loadCustomerWithOrders() etc.

Alternative approachs are to use the OpenSessionInView/OpenEntityManagerInView pattern which holds the Hibernate Session open until your view has been rendered or use Value Objects/DTOS.

Personally I prefer to use OSIV and will optimise as necessary once I have identified any performance issues.

Upvotes: 3

Related Questions