简体   繁体   中英

How to speed up List access in JPA

In my mapper class, I always have to retrieve a list of departments from my company entity :

  @OneToMany(mappedBy = "company", orphanRemoval = true, cascade = CascadeType.ALL)
  public List<CompanyDepartments> getDepartments()
  {
    return departments; //java.util.List variable. 
  }

There are a couple thousand departments(about 2000+). I am trying to reduce the time taken to fetch company data and want to begin with the departments which are going to be fairly static in nature.

Option 1 : I can always have a private method in the mapper which populates a cache on the first load and return from the cache all the time.

But is there anything more simpler? I am probably not the first one to face this and wanted to know how I could approach this. Is there a known annotation that can be used. Like a @Singleton annotation on the variable in the entity ? (there is no such annotation obviously). What is the simplest way to make this list a singleton.

Just a typical spring mvc 3 application using spring data jpa for db interaction.

I suggest this link that solves the n +1 query problem ... How can i resolve the N+1 Selects problem?

Moreover you could put a cache (lvl 2) on your search service, if the data does not change during the life cycle of the application. http://docs.spring.io/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html

Another approach is to add to indexes on the db.

I hope I've given you all the answers about your question.

What you're experiencing is part of the "object-relational impedance mismatch". One solution would be to extend your object model so that you can use a left join fetch to load multiple companies including their departments using only one SQL statement.

The problem using this technique is that you can populate only one list at a time. Although it's nice & easy to define many sub-lists in the world of objects, it's hard to load all these lists at the same time (and therefor efficiently) from a relational database. However it can be done on Oracle using object- or XMLType queries.

The straight-forward way to get such data out of a RDBMS is by writing custom queries that match exactly the task at hand and provide only the data that is actually needed. Therefor you'd need not only one company class, but many - one for each task. - you'd actually do inheritance instead of attribution

BTW, that is why ORM is still considered the Vietnam of Computer science - easy to get started, but hard to succeed with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM