Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate override "lazy=false"

I am working on a new module in an existing project. The project already has a user table, a pojo and a corresponding mapping file. The problem is that they are fetching all the properties eagerly by mentioning lazy="false". But, in my module, I am doing lot of read & write in a single request, so I don't want to fetch eagerly. What I want to know is that, is it possible to create an another mapping file for the same table & same pojo to load all the properties lazily? I have tried by assigning different entity-name for the mapping files, but while deploying, I am getting the error "Repeated column in mapping for entity".

I saw this answer, but it says "do not map child", then how will I get the proxies?

like image 384
wolverine Avatar asked Aug 06 '14 15:08

wolverine


3 Answers

That's one major drawback for using EAGER fetching as the default strategy. Usually you'd have a LAZY children collection that you can eagerly fetch on a HQL query basis.

What's worth mentioning is that HQL/Criteria queries overrule the default fetch strategy (the one given by your entity mappings) so that you can explicitly specify what to fetch.

For Criteria queries, you might give a try to Criteria.setFetchMode FetchMode.LAZY, although it's deprecated.

Another way to overrule the EAGER fetching is to use a javax.persistence.fetchgraph. This way, you can specify what you want to fetch and all the EAGER fetching properties that were not included in the Entity Graph are going to be fetched lazily.

like image 133
Vlad Mihalcea Avatar answered Sep 28 '22 08:09

Vlad Mihalcea


I think, your question is to not to load associated entity , egarly ? for this when : FetchType.LAZY = Doesn’t load the relationships unless explicitly called via getter. FetchType.EAGER = Loads ALL relationships default

In your case , if my understanding is correct then use lazy="false" fetch="select" so it will select on demand via getter. check this url , it will give more clear idea : Hibernate XML Mapping: Lazy False or Fetch Select? A Short Primer On Fetching Strategies

like image 37
Rudra21 Avatar answered Sep 28 '22 06:09

Rudra21


The point Hibernate mapping setting lazy = 'false' is making, is that you can map the same table twice if you use two different java classes. In your case, if you know for a fact that setting lazy="true" will suffice:

  1. create empty subclass of your pojo
  2. map your subclass the way you want to the same user table (for examply copy-pasting the existing mapping and changing lazy property value)
  3. in the module you create only use the subclass
like image 22
Deltharis Avatar answered Sep 28 '22 06:09

Deltharis